尽管条件不佳,while循环也不会停止

时间:2019-01-06 19:31:11

标签: 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;
}

2 个答案:

答案 0 :(得分:2)

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

#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;
}

答案 1 :(得分:0)

以下代码更安全,无需将cnd定义为类似于cnd[1]的数组:

#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("%1s", &cnd);
}

return 0;
}

运行代码时,会遇到以下错误,这是不言自明的。

[Error] ISO C++ forbids comparison between pointer and integer [-fpermissive]

表示while(cnd != 'n')

中的错误
相关问题