简体   繁体   中英

How format specifiers works with scanf in loop in C?

This code works correctly:

int main()
{
    int i,n=2;
    char str[50];

    for (i = 0; i < n; i++)
    {
        puts("Enter a name");
        scanf("%[^\n]%*c", str);
        printf("%s\n", str);
    }

return 0;
}

And reads two input, writes them.

Questions:

  1. What is %[^\n]%*c ? especially %*c ? How it works?
  2. When i change that line to scanf("%[^\n]", str) it does not take second input.why?

In scanf , %*c means that take one character of input, but don't actually store it in anything. So try to visualize this. In the first run of the loop, when you enter, say, behzad namdaryan , stdin will look something like this:

behzad namdaryan\n

Now, %[^\n] takes input as a string until it reaches \n . It will NOT count \n in the input, it'll leave it there. So if this were scanf("%[^\n]", str); in the loop instead, after the first run, stdin would look like this:

\n

As you can see, \n is still there. Now every time it does scanf again, it'll immediately find \n and leave it there and won't actually prompt you for input (because stdin is not empty). %*c takes care of this. Every time after you take the string as input, that %*c removes and disposes of the last \n in the stream so the stream becomes empty and you can take input again.

In a scanf format string, %[^\n] says to match all characters other than a new-line character. %*c says to match a character but not assign it to an input.

Since %[^\n] will match all characters until it finds a new-line character, the %*c will consume that new-line character without storing it. The characters matched by %[^\n] will be stored in str .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM