I met a buffer problem, my code is as follows (bold font):
#include
#include
#include
struct Student
{
int stu_id;
char stu_name[10];
int stu_age;
char stu_professional[10];
};
void rand_output(Student s)
{
printf("\t ID\tname\tage\tpro\n");
printf("\t%d\t%s\t%d\t%s\n",s.stu_id,s.stu_name,s.stu_age,s.stu_professional);
}
int main()
{
char answer='Y';
int get_randNumber;
Student stu[3]={{201301,"Ken",18,"computer"},{201302,"Mary",17,"computer"},
{201303,"Jack",18,"computer"}};
while (toupper(answer)=='Y')
{
// fflush(stdin); // Assuming it is commented
srand((unsigned)time(NULL));
get_randNumber=rand()%(2-0+1)+0;
rand_output(stu[get_randNumber]);
/*fflush(stdin);If the line is commented out,
The following code will not be executed in the second to(while loop will be aborted). Why is there such a situation?
Now, I would like to know its compiler theory.*/
printf("\tYou like to continue anyway?(Y or N):");
scanf("%c",&answer);
system("cls");
}
return 0;
}
Regards,
Ken

VulpesPosted Oct 13, 2013, 4:38 AM
Ken HPosted Oct 14, 2013, 10:02 PM
VulpesPosted Oct 14, 2013, 8:42 AM
On the second iteration scanf reads the '\n' left behind from the first iteration.
When calling scanf multiple times, you have to remember to clear the buffer each time to avoid this sort of problem.
Ken HPosted Oct 13, 2013, 7:26 PM
thank for you.