ipkiss ipkiss - 3 years ago 152
C Question

scanf() leaves the new line char in buffer?

I am learning C and have some questions. I know my questions may be a common question but I could not find the answer.
I have the following program:

int main(int argc, char *argv[])
int a, b;
char c1, c2;
printf("Enter something: ");
scanf("%d",&a); // line 1
printf("Enter other something: ");
scanf("%d", &b); // line 2

printf("Enter a char: ");
scanf("%d",&c1); // line 3
printf("Enter other char: ");
scanf("%d", &c2); // line 4

printf("Done"); // line 5


return 0;

As I read in the C book, the author say that scanf() left a new line character in the buffer, therefore, the program does not stop at line 4 for user to enter the data, rather it stores the new line character in c2 and moves to line 5. Is that right?
However, I was wondering this only happen with char data types? Because I did not see this problem with int data types as in line 1, 2, 3. It is right?


Answer Source

The scanf function removes whitespace automatically before trying to parse things other than characters. The character formats (primarily %c) are the exception; they don't remove whitespace.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download