Reputation: 25
I am writing a piece of code and in one part of my code I am using a switch statement in C language. if I press n it exits correctly if I press y it will infinite loop the default statement until I press control c. what am I doing wrong here. been changing the while statement but can't find the right one.
int main()
{
char ans;
printf("DO you want to continue?");
scanf("%c", &ans);
do
{
switch(ans)
{
case 'y':
some stuff...
printf("DO you want to continue?");
scanf("%c", &ans);
break;
case'n':
printf("BYE");
break;
default:
printf("error, you must enter y or n");
continue;
}
}
while (ans!='n');
return 0;
}
Upvotes: 0
Views: 1641
Reputation: 95325
When you press enter, the linefeed character \n
is added to the input stream. Your code does not anticipate this, because switch(ans)
only handles y
, n
or “everything else” (which includes the linefeed character).
To fix this, allow scanf
to ignore any preceding whitespace by changing your format string to " %c"
instead, e.g.
scanf(" %c", &ans);
// ^ space character inserted here
I think it would make more sense to move the scanf
call to inside the loop, like this:
int main()
{
char ans;
do
{
printf("DO you want to continue?");
if (scanf(" %c", &ans) != 1)
break;
switch(ans)
{
case 'y':
// some stuff...
break;
case 'n':
printf("BYE");
break;
default:
printf("error, you must enter y or n");
continue;
}
}
while (ans!='n');
}
Don't forget to always check the result of scanf()
. It will return the number of items successfully scanned (in your case, you want it to return 1). If it returns 0 or a negative number, then another problem has occurred.
Upvotes: 1