【问题标题】:specifying getchar() to Yes / No response before proceeding在继续之前将 getchar() 指定为 Yes / No 响应
【发布时间】: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 我正在学习并使用实用的方法,因为这是我最好的学习方式。你可能是一个既能读书又能做的人。恭喜。到目前为止,我对自己所做的事情印象深刻。遗憾的是,您的评论并没有那么有帮助。

标签: c loops scanf getchar


【解决方案1】:

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

我看到了另一个库,它为我提供了一些简化问题的选项。

#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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-17
    • 2020-01-18
    • 2014-07-12
    • 2016-04-02
    • 2012-11-17
    • 1970-01-01
    相关资源
    最近更新 更多