【问题标题】:While loop in CC语言中的while循环
【发布时间】:2015-03-09 19:18:29
【问题描述】:

谁能解释一下为什么当我输入字符'Q'时我的while循环不会结束?即使我在用户输入“Q”时将布尔值设置为 false,它仍会继续循环,它应该在 char input 的 scanf 之后结束。

我的代码:

#include <stdio.h>
typedef int bool;
#define true 1
#define false 0

int main(void) {
    char input;
    char output;
    bool tf = true;

    printf("Welcome to the Coder!\n");

    while (tf) {
        printf("Choose Input (H,A,B,Q) : ");
        scanf_s(" %c\n", &input);

        if (input == 'Q') {
            tf = false;
        }
        else {
            printf("Choose Output (H,A,B) : ");
            scanf_s(" %c\n", &output);
        }
    }

    return 0;
}

【问题讨论】:

  • 你在输入 Q 后是否按下回车键?
  • 还有另一个 scanf 问题?
  • 是的,我确实按了输入

标签: c while-loop


【解决方案1】:

问题是scanf_s 的奇怪情况。根据MSDN,您使用以下语法读取单个字符:

scanf_s(" %c", &input, 1);

scanf_s 中删除 \n 并添加 1 参数,以便它知道只能读取 1 个字符。

【讨论】:

  • 这解决了问题,谢谢。我真的不需要 %c 之后的 \n
【解决方案2】:

我怀疑您在控制台上输入了小写字母 q:

我建议您将代码更改为:

if (input == 'Q' || input == 'q') {
    tf = false;
}

【讨论】:

  • 或者就此而言,#include &lt;ctype.h&gt;if(toupper(input) == 'Q')
【解决方案3】:

你应该添加如果

(input == 'Q' || input == 'q') 

还有你为什么加typedef int bool;?这是不需要的。

我将scanf_s 替换为scanf,因为我的编译器无法识别它(意外解决问题。

因为它更好。当我编译这个没有错误。

已编译->Compiled Code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2021-03-06
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    相关资源
    最近更新 更多