为什么这段代码永远循环?

时间:2014-03-08 09:37:40

标签: c while-loop infinite-loop

我是c的新手,遇到这个奇怪的问题:我想写一个c代码让用户输入命令并做一些工作,这是我的代码:

int main()
{
  const int size = 100;
  while(1){
    char* currentDir;
    if((currentDir = getcwd(currentDir, 1024)) == NULL) {
      fprintf(stderr, "getcwd failed.\n");
      exit(0);
    }
    printf("%s > ", currentDir);

    char *command;
    command = (char*)calloc(size, sizeof(char));
    scanf("%[^\n]", command);
    if(strcmp("exit", command) == 0) {
      printf("%s\n", command);
      exit(0);
    }
    else {
      //do jobs based on user input
    }
    free(command);
  }
}

如果用户输入“exit”,程序将结束。但是如果用户输入其他字符串,如“ll”或其他东西,程序将保持循环,永远不会让用户输入另一个命令。为什么呢?

2 个答案:

答案 0 :(得分:2)

这一行:

scanf("%[^\n]", command);

将字符读取到但不包括换行符并将其放入command。换行符保留在输入缓冲区中。

当你下次循环执行该语句时,它会做同样的事情......除了它将遇到的第一个字符将是它上次看到的相同的换行符。净结果:它将command设置为空字符串,并为下一个调用留下换行符。等等。

您需要使用该换行符。

答案 1 :(得分:0)

  1. 您需要检查scanf
  2. 的返回值
  3. 小心缓冲区溢出
  4. 需要吃新行