Here is my c code:
int main()
{
int a;
for (int i = 0; i < 3; i++)
scanf("%d ", &a);
return 0;
}
When I input things like 1 2 3
, it will ask me to input more, and I need to input something not ' '.
However, when I change it to (or other thing not ' '
)
scanf("%d !", &a);
and input 1 ! 2! 3!
, it will not ask more input.
The final space in scanf("%d ", &a);
instructs scanf
to consume all white space following the number. It will keep reading from stdin
until you type something that is not white space. Simplify the format this way:
scanf("%d", &a);
scanf
will still ignore white space before the numbers.
Conversely, the format "%d !"
consumes any white space following the number and a single !
. It stops scanning when it gets this character, or another non space character which it leaves in the input stream. You cannot tell from the return value whether it matched the !
or not.
scanf
is very clunky, it is very difficult to use it correctly. It is often better to read a line of input with fgets()
and parse that with sscanf()
or even simpler functions such as strtol()
, strspn()
or strcspn()
.
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