I was writing a code to take a space-separated string input for a multiple time in between a loop. I saw that %[^\n]s
did not work in loop but %[^\n]%*c
did. My question is why %[^\n]s
did not work. Here is my code:
#include<stdio.h>
main(){
while(1){
char str[10];
scanf("%[^\n]s",str);
printf("%s\n",str);
}
return 0;
}
The format specifier %[^\n]
means "read a string containing any characters until a newline is found". The newline itself is not consumed. When the newline is found, it is left on the input stream for the next conversion.
The format specifier %*c
means "read exactly one character and discard it".
So the combination
scanf( "%[^\n]%*c", str );
means "read a string up to the newline character, put the string into the memory that str
points to, and then discard the newline".
Given the format %[^\n]s
, the s
is not part of the conversion specifier. That format says "read characters until a newline is found, and then the next character should be an s
". But next character will never be an s
, because the next character will always be the newline. So the s
in that format serves no purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With