I'm sorry for this silly question. I have C program to prompt user to enter age and name and
then print the age and name to the screen. This is my exercise that I read from book.
This the program:
#include <stdio.h>
int main (void) {
int age;
char name[20];
puts("Enter your age:");
scanf("%d",&age);
fflush(stdin);
puts("Enter your name:");
scanf("%s",name);
printf("Your age is %d
",age);
printf("Your name is %s
",name);
return 0;
}
When I enter extra characters to the first scanf()
the program terminates and assign the extra characters to the next scanf()
And then I changed the code, and add function named clear_buff()
and using the fgets
function within the clear_buff()
to read the remaining characters on stream.The code work as I expected.
#include <stdio.h>
#define MAXLEN 80
void clear_buff(void);
int main (void) {
int age;
char name[20];
puts("Enter your age:");
scanf("%d",&age);
clear_buff();
puts("Enter your name:");
scanf("%s",name);
printf("Your age is %d
",age);
printf("Your name is %s
",name);
return 0;
}
void clear_buff(void){
char junk[20];
fgets(junk,MAXLEN,stdin);
}
My question is why fflush(stdin)
not working in this program?
The book says that fflush
function clear any buffered data on the stream.And I know that
fflush()
function is the C standard function if working with I/O stream.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…