Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why %[^\n]s does not work in loop?

Tags:

c

string

loops

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]sdid 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;
}
like image 642
biswas N Avatar asked Feb 09 '23 09:02

biswas N


1 Answers

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.

like image 114
user3386109 Avatar answered Feb 11 '23 23:02

user3386109