Home > Software design >  Print a string without knowing max size [closed]
Print a string without knowing max size [closed]

Time:10-03

I am supposed to print out Number of letters in a word given by the user. I struggle to find out how i am supposed to declare the array when i dont have the size of the string. I thought of using gets and then a for loop but can’t figure out how to define char before doing this.

CodePudding user response:

When you obtain the string - say, with scanf() or fgets() - you can specify a maximum "field width", i.e. the maximum number of characters to read into your buffer. So, you first set the buffer size, then you read into it.

Now, after you've read the string, you can determine it's length the usual C way with strlen() on your buffer. Alternatively, if you're using scanf(), you can use the "%n" specifier to store the number of characters consumed, so that scanf("Is%n", buffer, &count); will scan the string into the 50-chararacter-long buffer and the number of characters into count.


PS - Don't use the gets() function though...
Why is the gets function so dangerous that it should not be used?

CodePudding user response:

Counting characters in a word entered by the user is easy. Set a counter to zero. Read one character at a time (e.g., using getchar). If the character is a letter, increment the counter and continue the loop. If it is not a letter or the attempt to read fails (e.g., getchar returns EOF), exit the loop and print the value of the counter. For embellishment, you might add code to ignore white space before the letters start, to ignore white space after the letters end (until a new-line character is seen), and/or to report a warning if any other characters are seen. –

Eric Postpischil

  • Related