In the loop in the code below, scanf("%[^\n]s",array)
is not working. It does not wait for input and gets skipped. But a space before %
fixes the issue. Why?
Here is the wrong program:
#include <string.h>
#include <stdio.h>
int main()
{
int t;
scanf("%d",&t);
while(t--){
char arr[199];
scanf("%[^\n]s",arr);
printf("%s",arr);
}
return 0;
}
Here is right code:
#include <string.h>
#include <stdio.h>
int main()
{
int t;
scanf("%d",&t);
while(t--){
char arr[199];
scanf(" %[^\n]s",arr);
printf("%s",arr);
}
return 0;
}
Why does it need a space before %
for it to work as expected?
If we enter the values separated by space, the function returns when space is encountered but the values after space remains in the input buffer. That's why the second scanf() function will not wait for user input, instead it takes the input from the buffer.
In C, %n is a special format specifier. In the case of printf() function the %n assign the number of characters printed by printf(). When we use the %n specifier in scanf() it will assign the number of characters read by the scanf() function until it occurs. Key points: It is an edit conversion code.
That means the next time you read from standard input there will be a newline waiting for you (which will make the next scanf() call return instantly with no data). To avoid this, you can modify your code to something like: scanf("%c%*c", ¤tGuess);
What's the use of scanf("%[^\n]% *c") in C programming? It is used to accept string which have whitespace in between.
First of all, the trailing s
is not part of the %[
format specifier, so remove it and lets talk about %[^\n]
.
Now, what %[^\n]
tells scanf
to do is scan everything until a newline character ('\n'
) or EOF
, whichever comes first, and stores it in its corresponding argument, in this case, arr
.
And here is the catch: %[^\n]
fails if the first character to be read is a \n
.
'Wait', you say. 'I did not type in a lone enter. So, why'd it fail?'. True. You did not. But remember the Enter you pressed for the previous line? Turns out, the previous call to scanf
grabs everything until the \n
, leaves the \n
there and returns. So, in the next iteration of the loop, the scanf
sees this \n
character left over by the previous call to scanf
, fails and returns 0.
As for the space, it is a whitespace character. And a whitespace character in scanf
instructs it to scan and discard all whitespace characters until the first non-whitespace character. So, it removes the \n
(since it is a whitespace character) and scanf
will wait for further input.
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