满足条件后,为什么我的while循环不执行其功能?

时间:2019-10-01 22:47:42

标签: c

作为测试,我试图做一个非常简单的while循环。本质上,while循环中的语句询问您是否要继续。如果输入正确的字符,它将再次询问您相同的问题。如果输入任何其他字符,则将不再满足while循环的条件,并且应退出while循环。但是,循环甚至不会执行一次,并且程序一开始就立即结束。这使我认为我的状况有问题,但据我所知,这是符合条件的。

我尝试仅使用整数作为条件构造while循环(只要变量不等于特定值,循环就会运行。只要变量等于该值,循环就会循环结束。)该程序成功运行,但是我无法使用字符作为输入来使类似代码发挥相同的作用。

这是我的行号无效的代码:

#include <stdio.h>

void main(void)
{
    char word="a";
    while(word == "a") 
    {   
        printf("\ntest. enter a to continue");
        scanf("%c", &word);
    }
}

我期望的是

test. enter a to continue

在我输入“ a”后,应重复相同的语句,如果输入其他任何内容,则程序应结束

我实际上得到的是:

--------------------------------
Process exited after 0.6154 seconds with return value 4210688
Press any key to continue . . .

这是我从任何成功的程序完成后得到的结果,但输出要在虚线上方。在这种情况下,虚线上方没有输出,这意味着程序结束时根本没有输出。

我没有错误消息,但确实有以下警告消息:

[Warning] initialization makes integer from pointer without a cast (line 5)
[Warning] comparison between pointer and integer  (line 6)

2 个答案:

答案 0 :(得分:2)

这些警告不仅仅是警告-它们是您的程序无法运行的原因。在程序的两个位置,将"a"更改为'a',以使用字符文字而不是字符串,您将被设置。

答案 1 :(得分:0)

比较字符串最好使用strcmp

编辑

比较字符串通常 使用strcmp更好。

此代码说明了在OP要求的特定情况下如何使用它:

#include <stdio.h>
#include <string.h>

int main(void)
{
   const char *initial_word = "a";
   char next_word [] = "b";

   const char *compare = "a";
   int condition = strcmp(initial_word, compare); //return 0 -> true

   while(condition == 0)
   {
        printf("Test: enter a to continue: \t");
        scanf("%s", next_word);

        if (strcmp(next_word, compare) != 0) condition = 1;
   }

}
相关问题