c - 尽管满足条件,但循环不会停止

标签 c

我想使用 while 循环在我的程序中插入一个条件。最后它会询问您是否要从头开始重复该程序。如果你输入'n'然后程序停止,如果你输入任何其他你继续。问题是即使你在 'n' 中写入它仍然会继续。我正在提供代码,以便您自己查看:

我没有给出程序的其余部分,因为它运行良好,只是循环本身才是问题所在。当我创建一个涉及整数的条件时它工作正常,只是当我想要一个 char 字符串时出现问题。

#include <stdio.h>
#include <stdbool.h>

int main()
{

  char cnd[1];

  while(cnd != 'n') {
    printf("Would you like to continue? If not, then type in 'n', if you do then type in anything else: ");
    scanf("%1s", &cnd);
  }
return 0;
}

最佳答案

为什么要使用字符数组??您可以只使用常规字符

#include <stdio.h>

int main(){
    char cnd;
    while(cnd != 'n') {
        printf("Would you like to continue? If not, then type in 'n', if you do then type in anything else: ");
        scanf("%c", &cnd);
    }
    return 0;
}

关于c - 尽管满足条件,但循环不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54065154/

相关文章:

c - 如何使用带信号的fork?

c - 下面的 C 代码在 Fedora 上运行,但在 RaspberryPi 1 上运行时出现段错误

c - 只读取一行的第一个字符

c - 递归搜索目录中的文件

c - 在位数组中有效地查找 '1' 的位置

c - 混合 fPIC 和非 fPIC 对象模块

c - 传递带参数的函数也是一个函数

c - 线程创建的顺序重要吗?

c - 字符数组的工作原理

c - 如何将 C 宏 (#define) 分离到 .h 和 .c 文件中