【发布时间】:2023-03-27 08:04:01
【问题描述】:
我在确定一些代码来指定用户输入时遇到了一些麻烦; n、N、y 或 Y。
如果用户输入了上述以外的任何内容,则会导致请求重新输入。
我已经移动了这段代码 - while (response != 'n' | 'N' | 'y' | 'Y') { 代码上下移动,这表明它没有提供我预期的结果。
我尝试了一些与 scanf 的组合,但看起来只能在循环中定义一次 to = response. Getchar 目前正在推广两次,第一个键输入和回车键。
我曾希望这样的事情会奏效,但它没有。
if (response != 'n' || response != 'N' || response != 'y'|| response != 'Y') {
我认为这可能是我试图解决此问题的方法,并结合一些基本问题了解您可以使用这些命令实际做什么。
在这里进行一些搜索,似乎表明要避免 scanf 和 getchar 任何机会,但这就是我到目前为止所看到的全部。
我也在努力理解如何从第一个 Y/N 循环过渡到第二个循环 while > if > while。
抱歉,有很多问题,但 3 小时,我正在浪费时间。
任何关于什么是不正确的建议以及重新阅读的内容将不胜感激。
/* Play game yes / no. */
printf("Would you like to play [y|n]?\n");
response = getchar();
/* If response is not "Y" or "N" expected */
while (response != 'n' | 'N' | 'y' | 'Y') {
printf("Please enter either 'y' or 'n'.");
response = getchar();
}
/* If response is "no" exit program */
if (response == 'n' || response == 'N') {
printf("No worries... another time perhaps... :)\n\n");
exit(EXIT_SUCCESS);
}
/* While loop to continue game */
while (response == 'y' || response == 'Y') {
```
【问题讨论】:
-
while (response != 'n' | 'N' | 'y' | 'Y') {并没有做你认为的那样...... -
while (response != ('n','y')) { 似乎允许输入 Y 但不允许输入 N。我是否更正 (!=) 不等于?跨度>
-
您真的应该阅读有关 C 语言的教程。你似乎对很多事情做出了疯狂的猜测,其中大部分都是不正确的。你知道
x | y做什么吗?你知道(x, y)做什么吗?这些是基本的 C 运算符,你不知道它们的作用。 -
试着为
response != 'n' || response != 'N'画一个真值表,你会发现哪里出了问题。 -
@Tom Karzes 我正在学习并使用实用的方法,因为这是我最好的学习方式。你可能是一个既能读书又能做的人。恭喜。到目前为止,我对自己所做的事情印象深刻。遗憾的是,您的评论并没有那么有帮助。