问题描述
所以我想询问用户是否愿意重复我的计划,现在,然后我得到一个奇怪的结果。它不会发生,每次我没有带能够找出什么触发了。
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.
要我来说,它看起来像它后,我输入Q以repeatProgram,而不是'Q'被分配'回归',但我不知道为什么。
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:
的退出输入q,继续输入y。的
小号
的您输入S,这不是一个有效的选项。的
输出当它失败:
的退出输入q,继续输入y。的
q
的您输入的
,这不是一个有效的选项。的
在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.
推荐答案
出现这个问题,因为你的 scanf函数
读 \\ n
您第一次输入之后。为了避免这种情况的改变你的 scanf函数
声明如下:
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'
输出:
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 ~
$
这篇关于用C重复程序功能衰竭,scanf函数关系吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!