I would imagine that the newline which the earlier call to scanf() did not read in (the newline which you entered by pressing <ENTER> after the number you entered) is still sitting in the buffer, and when the program gets to the getchar(), there is a newline there waiting for it, so it does not need you to press <ENTER> again.
Try something like this:
Code:
#include <stdio.h>
int main()
{
int c;
int age;
printf("please enter your age");
scanf("%d", &age);
while ((c = getchar()) != EOF && c != '\n') {
;
}
if (age < 40) {
printf("You are not old enough!\n");
} else if (age == 40) {
printf("You are borderline!\n");
} else {
printf("You're pushing it buddy!");
}
getchar();
return 0;
}
This code
Code:
while ((c = getchar()) != EOF && c != '\n') {
;
}
makes repeated calls to getchar() as long as the condition is not EOF or a '\n' (newline) - it basically 'eats' every remaining character (including the newline) in the buffer. The ; on the line all by itself is a nulll statement - all of the actual work is done in the while statment one line above, but syntactically, the semicolon ';' is necessary so we add it - it could have been placed right after the while statement on the same line like so:
Code:
while ((c = getchar()) != EOF && c != '\n') ;
But I prefer to have it out on its own line so there is no mistaking that it is indeed a null statement - but each to his own on style issues like that one.
As to the '\n', that is your newline (as I mentioned above) - it is the way that you represent a character that does not really have a representation - similar characters would be '\t' for a tab, and '\b' for a backspace. A ' ' would be a space obviously.