在继续之前将 getchar() 指定为 Yes / No 响应

问题描述

我在确定一些代码来指定用户输入时遇到了一些麻烦; n、N、y 或 Y。

如果用户输入除上述内容之外的任何内容,则会导致请求重新输入。

我已经移动了这段代码 - while (response != 'n' | 'N' | 'y' | 'Y') { 代码上下移动,这表明它没有提供我预期的结果。

我已经尝试了几种与 scanf 的组合,但看起来只能在循环中定义一次 = 响应。 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') {
 ```

解决方法

对于下一个寻求类似答案并且同样从寻求声誉的无偿专业人士那里获得的价值微乎其微的人。

有人向我展示了另一个库,它为我提供了一些简化问题的选项。

#include

这让我可以将任何用户的大写条目减少为小写,以便下一行代码更容易处理。这对于像我这样对 C 运算符的理解不够完美的人会很有帮助。

// 吃掉新行代码将修复 Getchar() 的重复打印问题

A thank you to the previous thread on that issue.

/* If response is not "Y" or "N" as expected prompt user to enter again */
response = tolower(response); // reduces user capital entry complexity
while (response != 'y' && response != 'n'){
printf("Please enter either 'y' or 'n'.");
response = tolower(response); // reduces user capital entry complexity
response = getchar();
while (getchar() != '\n'); // eat up the new line