0

When I use the lines:

char *sentence = (char *)malloc(100);
scanf("%[^\n]%*c",sentence);

to read a line from stdin into the buffer, sentence, but then have:

printf("%s\n", sentence);

afterwards, I notice that printf prints the entire sentence as opposed to just the first word from the line. Why is this? Shouldn't printf take only up to the first white space? If not, how does it know where to stop? Sentence surely doesn't end in a "\n" since it doesn't read the last return, and we used *c to read one character and not store it.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
M. dike
  • 1
  • 1
  • 2
    1. Cast for malloc is bad https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Ed Heal Feb 17 '18 at 19:13
  • 1
    2. Perhaps read the manual page for scanf https://linux.die.net/man/3/scanf – Ed Heal Feb 17 '18 at 19:13
  • the '%s' in the 'printf()' will output until a NUL byte. It does not stop at 'white space' – user3629249 Feb 17 '18 at 21:14
  • when calling any of the `scanf()` family of functions: 1) always check the returned value (not the parameter value) to assure the operation was successful. 2) when using the input/format specifier `%[...]` and/or `%s` always include a MAX CHARACTERS modifier that is 1 less than the length of the input buffer so the input buffer cannot be overflowed (note: those two input/format specifiers always append a NUL byte to the input.) If the incoming characters overflow the input buffer, the result is undefined behavior and can lead to a seg fault event. – user3629249 Feb 17 '18 at 21:18
  • when calling any of the heap allocation functions (malloc, calloc, realloc) 1) always check (!=NULL) the returned value to assure the operation was successful – user3629249 Feb 17 '18 at 21:27

1 Answers1

4

The scanset doesn’t contain ' ' so it won't stop when it gets one. The scanf would be

scanf("%[^ \n]%*c",sentence);

This would basically stop when it finds the \n or ' ' and this way you will get the first word if it is space separated.(Though if there is space before the first word then sentence will not be updated because the scanf sees a character from scanset) Notice one thing that your buffer can hold 100 characters (pointed by char* sentence) so use it like this

scanf("%99[^ \n]%*c",sentence);

One less than what it can hold because there is nul terminating character to hold also.

Furthermore, if you wanted to get a single word you could do something simpler like this:-(This solution will work in the scenario where a words is prefixed with whitespace because %s format specifier skips over them and stores the non-whitespace until a white space charcaters is encountered or the maximum charcaters specified by length is scanned)

scanf("%99s",sentence);
user2736738
  • 30,591
  • 5
  • 42
  • 56