aman awasthi aman awasthi - 1 month ago 19
C Question

what do modifiers like whitespace do in scanf?

#include<stdio.h>
void main()
{
char a,b;
printf("enter a,b\n");
scanf("%c %c",&a,&b);
printf("a is %c,b is %c,a,b");
}


1.what does the whitespace in between the two format specifiers tell the computer to do?
2.do format specifiers like %d other than %c clean input buffer before they read from there?

Answer

1.what does the whitespace in between the two format specifiers tell the computer to do?

Whitespace in the format string tells scanf to read (and discard) whitespace characters up to the first non-whitespace character (which remains unread)1. So

scanf("%c %c",&a,&b);

reads a single character into a (whitespace or not), then skips over any whitespace and reads the next non-whitespace character into b.

2.do format specifiers like %d other than %c clean input buffer before they read from there?

Not sure quite what you mean here - d will skip over any leading whitespace and start reading from the first non-whitespace character, c will read the next character whether it's whitespace or not. Neither will flush the input stream, nor will they write to the target variable if the directive fails (for example, if the next non-whitespace character in the input stream isn't a digit, the d directive fails, and the argument corresponding to that directive will not be updated).


  1. N1570, §7.21.6.2, para 5: "A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails."

Comments