C 中 yes/no 后按 Enter 键继续
这里的新程序员只有一些少量的 Java 经验,尝试用 C 编写一些东西。我想问某人是/否问题,根据他们的答案做一些事情,然后让他们按 Enter 继续。我遇到两个问题:
1.) 我无法让程序接受“y”、“Y”或“是”作为答案。我可以让它接受其中之一,但不能接受全部三个。 “逻辑或”运算符||不工作。 2.)如果没有两个“刷新”命令,我无法让它停止在“按 Enter 继续”:
while (getchar() != '\n');
我拥有并尝试使用的代码如下:
int main (int argc, const char * argv[]) {
printf("Would you like to continue? Please press y or n.\n");
if(getchar() == 'y'){
printf("You pressed yes! Continuing...");
}
else{
printf("Pressed no instead of yes.");
}
//flush commands go here
printf("\nPress ENTER to continue...");
if(getchar()=='\n'){
printf("\nGood work!");
}else{
printf("Didn't hit ENTER...");
return 0;
}
任何帮助将不胜感激,谢谢。
New programmer here with only some minor Java experience trying my hand at writing something in C. I want to ask someone a Yes/No question, do something depending on their answer, then ask them to press Enter to continue. I'm having two problems:
1.) I can't get the program to accept 'y', 'Y', or "Yes" as answers. I can get it to accept one, but not all three. The "logical OR" operator || isn't working.
2.) I can't get it to stop at "Press Enter to Continue" without two "Flush" commands of:
while (getchar() != '\n');
The code I have and am trying to use is as follows:
int main (int argc, const char * argv[]) {
printf("Would you like to continue? Please press y or n.\n");
if(getchar() == 'y'){
printf("You pressed yes! Continuing...");
}
else{
printf("Pressed no instead of yes.");
}
//flush commands go here
printf("\nPress ENTER to continue...");
if(getchar()=='\n'){
printf("\nGood work!");
}else{
printf("Didn't hit ENTER...");
return 0;
}
Any help would be appreciated, thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设你工作在*nix环境下,
您可以创建一个缓冲区来依次存储传入的字符。
您有两种情况:
对于所有其他情况,您可以盲目地说输入不正常!
对于情况 1,i 应为
1
,character
应为 'y' 或 'Y'对于情况 2,i 应为
3
,string
应为“Yes”任何其他情况都是不正确的。这是代码:
我建议使用这样的代码。
Assuming that you are working in *nix environment,
You can create a buffer to store the incoming characters one after the other.
You have two cases:
For all other cases you can blindly say that the input is not OK!
For case 1, i should be
1
and thecharacter
should be 'y' or 'Y'For case 2, i should be
3
and thestring
should be 'Yes'Any other case is incorrect. Here is the code:
I would recommend using something like this.
首先,您可能想保存第一个
getchar()
的结果来测试每个可能的值例如,
第二个测试中“enter”部分跳过的原因是,当您键入“y”或“n”时,您在发送输入后按 Enter -
\n
仍在缓冲区中,并且它由下一次调用getchar()
拉取First off you might like to save the result of the first
getchar()
to test each possible valueeg
The reason the "enter" part skips for the second test is because when you type 'y' or 'n' you press enter after to send your input - the
\n
is still in the buffer and it pulled by the next call togetchar()