C 而loop赢了';即使处于爆震状态,也不能停止

C 而loop赢了';即使处于爆震状态,也不能停止,c,C,我想使用while循环在程序中插入一个条件。最后,它会询问您是否要从头开始重复该程序。如果键入“n”,则程序停止,如果键入其他内容,则继续。问题是,即使在“n”中写入,它仍然会继续。我给出了代码,以便您可以自己查看: 我不会给出程序的其余部分,因为它工作得很好,问题在于循环本身。当我创建一个包含整数的条件时,它工作得很好,但当我需要一个字符字符串时,出现了一个问题 #include <stdio.h> #include <stdbool.h> int main() {

我想使用while循环在程序中插入一个条件。最后,它会询问您是否要从头开始重复该程序。如果键入“n”,则程序停止,如果键入其他内容,则继续。问题是,即使在“n”中写入,它仍然会继续。我给出了代码,以便您可以自己查看:

我不会给出程序的其余部分,因为它工作得很好,问题在于循环本身。当我创建一个包含整数的条件时,它工作得很好,但当我需要一个字符字符串时,出现了一个问题

#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;
}
#包括
#包括
int main()
{
char-cnd[1];
而(cnd!=“n”){
printf(“您想继续吗?如果不想继续,请键入'n',如果想继续,请键入其他内容:”;
scanf(“%1s”和cnd);
}
返回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;
}
#包括
int main(){
char-cnd;
而(cnd!=“n”){
printf(“您想继续吗?如果不想继续,请键入'n',如果想继续,请键入其他内容:”;
scanf(“%c”和cnd);
}
返回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;
}
#包括
int main(){
char-cnd;
而(cnd!=“n”){
printf(“您想继续吗?如果不想继续,请键入'n',如果想继续,请键入其他内容:”;
scanf(“%c”和cnd);
}
返回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;
}

这是指
中的错误,而(cnd!=“n”)

以下代码更安全,无需将
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;
}

这是指
while(cnd!=“n”)中的错误。

cnd的实际类型是char*,在“while”中比较char*和char。您的编译器应该已经警告过您了。cnd的实际类型是char*,在“while”中比较char*和char。您的编译器应该已经警告过您了。谢谢,这确实解决了问题。但我实际上试图避免使用没有字符串的char,因为它通常会导致程序出现其他问题。我在上面的回答中进行了详细阐述。您的回答很好(+1),正如在对问题本身的评论中所指出的,
scanf()
使用“%1s”格式说明符将在指定的地址写入2个字符,因为它必须写入一个终止NUL字符。在Andra的回答中使用“%c”。谢谢,这确实解决了问题。但我实际上试图避免使用没有字符串的char,因为它通常会导致程序出现其他问题。我在上面的回答中进行了详细阐述。您的回答很好(+1),正如在对问题本身的评论中所指出的,
scanf()
使用“%1s”格式说明符将在指定的地址写入2个字符,因为它必须写入一个终止NUL字符。在Andra的回答中使用“%c”。谢谢,这确实解决了问题。但我实际上试图避免使用没有字符串的char,因为它通常会导致程序出现其他问题。我在上面的回答中详细阐述了。谢谢,这确实解决了问题。但我实际上试图避免使用没有字符串的char,因为它通常会导致程序出现其他问题。我在上面的回答中详细阐述了这一点。