【问题标题】:detecting a newline in fgets [duplicate]在 fgets 中检测换行符 [重复]
【发布时间】:2013-11-25 17:01:02
【问题描述】:

我正在尝试创建一个 C 程序,用作 UNIX 系统的简单命令行解释器。我使用 fgets() 读取用户输入,然后将输入存储在要解析的缓冲区中。如果唯一的用户输入是按回车,我想重新发出提示。有没有办法检测返回键是否是在提示符下输入的唯一键?下面是我目前尝试过的一段 sn-p 代码:

for (;;) {
    printf("$prompt$ ");
    fflush(stdout);

    fgets(commandBuffer, 200, stdin);

    /* remove trailing newline:*/
    ln = strlen(commandLine) - 1;
    if(commandLine[ln] == '\n')
        commandLine[ln] = '\0';

    /* attempt to handle if user input is ONLY return key:*/
    if(commandLine[0] == '\n')
        continue;

【问题讨论】:

  • 对于(罕见的)fgets() 返回零长度字符串的情况,代码将失败。
  • 这可以通过检查 sizeof 来解决。
  • @JFA 请详细了解“检查 sizeof”如何提供帮助。
  • @chux 我在回复 alk 的声明,但现在我想起来了,我想你想要的是 strlen。我在考虑 sizeof 做别的事情。

标签: c shell prompt fgets


【解决方案1】:

删除潜在新行的流行单行是

if (fgets(commandBuffer, 200, stdin)) {
  commandBuffer[strcspn(commandBuffer, "\n")] = '\0';

strlen(commandLine) 返回 0 时会出现问题。当读取的输入行以 null 字符开头时会发生这种情况。

fgets(commandBuffer, 200, stdin);
ln = strlen(commandLine) - 1;  // ln could be outside 0...199  
if(commandLine[ln] == '\n')    // commandLine[ln] is then undefined behavior 

否则像@ensc一样执行。

if (fgets(commandBuffer, 200, stdin)) {
  ln = strlen(commandLine);
  while (ln > 0 && commandLine[ln-1] == '\n') {
    --ln;
  }
  commandLine[ln] = '\0';

【讨论】:

    【解决方案2】:

    你需要更换

     if(commandLine[0] == '\n')
    

    if(commandLine[0] == '\0')
    

    上面的代码用 nuls 替换换行符。

    【讨论】:

      【解决方案3】:
      ln = strlen(commandLine);
      while (ln > 0 && commandLine[ln-1] == '\n')
          --ln;
      commandLine[ln] = '\0';
      

      是一种更紧凑的解决方案,用于处理空输入等特殊情况。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-06
        • 1970-01-01
        • 2016-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多