When compiling to Linux with gcc, everytime the user inputs whatever answer, the program reaches the same part of the code in other iteration but doesn't waits for the input of the user, and instead feeds a newline to the scanf function, making the program print 'I don't get it!' every time... The program works, but still, I didn't want it to write 'I don't get it!', independent of the users' answer. Here's the specific part of the code.
do
{
printf("\n\nAnswer: (y/n) ");
scanf("%c", &ans);
//printf("\n->%c<-\n", ans); //just for debugging
if (ans == 'y')
{
age += v[0];
}
else if (ans != 'n')
{
printf("\nI don't get it!\n");
}
} while (ans != 'y' && ans != 'n');
These are the declarations:
char v[64];
char ans;
(This do..while loop is inside a 'for') What further puzzles me is the fact that the program compiles and runs exactly as I'd expect on Windows... (using MinGW) I've tried using fflush(stdin) before and/or after the scanf, but it didn't help. An important observation is that the first time it reaches this question it acts as expected.
(before the user answers)
Answer: (y/n)
I don't get it! // this gets written every time but the firstAnswer: (y/n) n
You are 21 years old!
If the user writes invalid input:
Answer: (y/n) w
I don't get it!
Answer: (y/n) // this line and the next one should simply not be printed
I don't get it!Answer: (y/n)
//(now it waits for user input)
Any ideas?
Edit
Fixed it:
(I declared an additional char buf[50]
)
do
{
printf("\n\nAnswer: (y/n) ");
fgets(buf, 50, stdin);
sscanf(buf, " %c", &ans);
if (ans == 'y')
{
age += v[0];
}
else if (ans != 'n')
{
printf("\nI don't get it!\n");
}
} while (ans != 'y' && ans != 'n');
Can someone tell me what is the problem with scanf?