Search code examples
cscanfformat-specifiers

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?

Solution

  • 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.