【问题标题】:I am trying to create a c program that will continuously take inputs from stdin till exit is entered我正在尝试创建一个 c 程序,该程序将不断从标准输入获取输入,直到输入退出
【发布时间】:2020-02-13 22:20:39
【问题描述】:

这是我写的代码:

#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;
}

但它似乎没有退出并陷入无限循环。

【问题讨论】:

  • fgets 返回的字符串将包含换行符 (\n)。尝试使用strncmp(str, str2, 4) != 0
  • str 第一次未初始化;也许使用不同的循环机制?
  • @AdrianMole 匹配,例如,exiting
  • @Neil - 很好发现!

标签: c cycle


【解决方案1】:

一种解决方案是使用:

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 是空的。

【讨论】:

  • 这可能是可以想象的最懒惰的方式,(也是最快的方式之一)我赞成。
  • @rohithp,很高兴为您提供帮助,将信用扩展到 Adrian MoleNeil
猜你喜欢
  • 1970-01-01
  • 2012-10-31
  • 1970-01-01
  • 2017-02-03
  • 2012-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-26
相关资源
最近更新 更多