问题
So I'm trying to ask the user if they would like to repeat my program and I am getting a weird result now and then. It doesn't happen everytime and I havn't been able to figure out what triggers it.
To me it looks like it is assigning the 'return' after I enter 'q' to repeatProgram instead of the 'q' but I have no Idea why.
The output when it works:
to exit enter q, to continue enter y.
s
you've entered s, that isn't a valid option.
The output when it fails:
to exit enter q, to continue enter y.
q
you've entered
, that isn't a valid option.
The code:
char RepeatProgramPrompt()
{
char repeatProgram;
do
{
printf("\nTo exit enter q, to continue enter y.\n");
scanf("%c%*c", &repeatProgram);
repeatProgram = tolower(repeatProgram);
if(repeatProgram != 'y' && repeatProgram != 'q')
{
printf("\nYou've entered %c, that isn't a valid option.\n", repeatProgram);
}
}while(repeatProgram != 'y' && repeatProgram != 'q');
return(repeatProgram);
}
So my question is, why is this happening? it will work fine for a bunch of tries and then just fail.
Sorry if I've formatted this wrong it is my first post.
回答1:
That problem occurs because your scanf
reads the \n
after your first input. To avoid this change your scanf
statement to this:
scanf("%c", &repeatProgram);
getchar(); // this will remove the excess '\n'
Output:
Sukhvir@Sukhvir-PC ~
$ ./test
To exit enter q, to continue enter y.
d
You've entered d, that isn't a valid option.
To exit enter q, to continue enter y.
s
You've entered s, that isn't a valid option.
To exit enter q, to continue enter y.
d
You've entered d, that isn't a valid option.
To exit enter q, to continue enter y.
q
Sukhvir@Sukhvir-PC ~
$
回答2:
Eat up the trailing whitespace characters with newline after scanf and it should work:
scanf("%c", &repeatProgram);
while(getchar() != '\n')
{
//do nothing
}
Sample output.
来源:https://stackoverflow.com/questions/19628381/repeat-program-function-failure-in-c-scanf-related