我正在尝试创建一个 c 程序,它将不断从 stdin 获取输入,直到输入 exit

I am trying to create a c program that will continuously take inputs from stdin till exit is entered

这是我写的代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define SIZE 50

int main(int argc, char *argv[])
{
  char str[SIZE];
  char str2[] = "exit";
  //fgets(str, sizeof str, stdin);
  while (strcmp(str, str2) != 0)
  {
    fgets(str, sizeof str, stdin);
    printf("%s", str);
  }
  return 0;
}

但是好像没有退出,一直卡在死循环中

一种解决方案是使用:

char str2[]="exit\n";

但是 do - while 循环最好:

int main () {    
    char str[SIZE];
    char str2[]="exit\n";
    do {
        fgets(str, sizeof(str), stdin);
        printf("%s",str);
    } while(strcmp(str,str2));
    return 0; 
}

因为在循环的第一次迭代中 str 是空的。