【问题标题】:while loop not executingwhile循环没有执行
【发布时间】:2012-04-10 03:17:14
【问题描述】:

我在程序中创建了一个 while 循环,程序到达了 while 循环,但它没有执行。我觉得我错过了一个非常小的错误,因为我已经查看了这么长时间的代码。

  int strbuf = 100;
  char string[strbuf];
  char *exit = "exit";
  while(!strcmp(string, exit)){
      printf("Enter a word to search. Enter exit to quit");
      scanf("%s", string);
      state = present(fIndex, string);
      if(state){
        printf("The word %s was found on line %d", string, state);
    }
}

编辑:输入来自键盘。 编辑编辑:新代码(同样的问题)

int strbuf = 100;
char string[strbuf];
char *exit = "exit";

printf("Enter a word to search. Enter exit to quit\n");
scanf("%s", string);
    while(!strcmp(string, exit)){
    state = present(fIndex, string);
    if(state){
        printf("The word %s was found on line %d", string, state);
    }
    else printf("The word %s was not found", string);
}

【问题讨论】:

  • 你不打算在while循环之前接受一次输入吗? string 在初始循环迭代中最初有垃圾。

标签: c loops while-loop


【解决方案1】:

阅读strcmp 的手册页:

strcmp() 函数比较两个字符串 s1 和 s2。它 返回 如果找到 s1,则为小于、等于或大于零的整数, 分别小于、匹配或大于 s2。

如果匹配,strcmp 将返回 0,如果两个字符串不匹配,则返回非零值。

因此while(!strcmp(string, exit)) 真的是说,当字符串匹配时,继续循环。

string 也未初始化并包含垃圾,导致未定义的行为。如果你的循环必须执行至少一次,要么先初始化它,要么使用do..while 循环。

【讨论】:

  • 他正在考虑这一点。条件为!strcmp(string, exit)
  • 零值表示两个字符串相等。只要字符串不相等,他就想运行循环。 while(strcmp(string, exit)) 将一直​​运行直到字符串相等。
  • @paxdiablo: 他有while(!strcmp(string, exit)),应该是while(strcmp(string, exit))while(strcmp(string, exit) != 0),我是不是看错了什么?他想留在循环内,直到用户输入"exit"。还是您要说明他应该在循环之前接受输入?
  • @paxdiablo:别担心,你有我一秒钟。还没吃早餐,已经快下午 2 点了,所以我以为我吃饱了。
  • @tnecniv:他正在检查字符串是否匹配,以及是否匹配以继续循环。当两个字符串不匹配时,该条件将导致循环终止。
【解决方案2】:

是的,它正在执行。 while 循环的 body 可能没有执行,但那是因为你正在做的是未定义的行为,在它被初始化为任何有用之前使用 string

一个简单的解决方法是改变:

char string[strbuf];

进入:

char string[strbuf] = {'\0'};

而且,为了便于阅读,您应该扩大比较,除非它们真的 布尔值,(而且,由于您在一些地方硬编码“退出”,我我不知道你为什么要把它作为一个变量):

while (strcmp (string, "exit") != 0) {

【讨论】:

    【解决方案3】:

    在将 stringexit 进行比较之前,您没有获得输入。放一个:

    printf("Enter a word to search. Enter exit to quit");
    scanf("%s", string);
    

    在你的 while 循环之前。

    【讨论】:

    • 嗯??是不是有什么讽刺的地方没有讲到这里??
    • DRY = "不要重复自己" - 当您可以将字符串设置为“exit”以外的其他内容时,无需在循环之前输入。我说了五次的事实它本身是一种元幽默,现在因为我不得不解释它而变得毫无用处:-) 没关系,我的妻子通常不会了解我奇怪的幽默品牌。认为自己很幸运,不必每天都忍受它。
    • 嗯,谢谢你的解释。顺便说一句,即使你不得不解释主要的笑话,你的最后两行也让我崩溃了 ;) URAWESOME ;)
    【解决方案4】:

    如果没有执行while循环,则表示!strcmp(string, exit)为假

    这意味着strcmp(string, exit)必须是tru(非0)

    strcmp 在匹配时返回 0,因此 stringexit 不同

    这是什么原因?您永远不会在字符串中输入值。建议将其更改为“do while”循环。

    【讨论】:

      【解决方案5】:

      此外,exit() 是一个标准的 C 函数(参见 stdlib.h)。 strExit 之类的东西可能更适合您的目标。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-22
        • 2015-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多