user648933
user648933

Reputation: 25

C programming, scanf() function

Does scanf put spaces in its buffer or input stream? If i say

scanf("%c %d %d", &character, &num1, &num2);

And now say

scanf("%c", &char2);

I know that enter will stay in the buffer but do the spaces count?

scanf("%c%d%d", &character, &num1, &num2);

Is this any different than the first part.

Also another thing. Can I somehow break scanf after user presses enter. If it presses enter after the num1 for ex. Input: i 5

Can i somehow make scanf stop after this even though it is waiting for one more input?

Upvotes: 0

Views: 259

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35154

A space in the format string of scanf will consume any white space (if any); Format specifier %d will also ignore any whitespaces before the actual number. So " %d" has the same effect as "%d". Format specifier %c will not ignore white spaces but read them in, so " %c" would be different than "%c". In your case, where %c is at the beginning of the format string of scanf("%c %d %d", ...) has the same effect as scanf("%c%d%d", ...).

If you want to allow to exit before everything is entered, I'd suggest to read in a complete "line" using fgets and then parse the input accordingly, e.g. using sscanf of strtok.

Upvotes: 3

Related Questions