【问题标题】:C: Why does the "Enter" key trigger output in this code?C:为什么在这段代码中“回车”键会触发输出?
【发布时间】:2017-03-19 13:05:42
【问题描述】:

这是我在“C 编程语言”中练习 1-13 的代码:

#include <stdio.h>

int main()
{
    int c, currentIndex, currentLength;

    currentLength = currentIndex = 0;

    while ((c = getchar()) != EOF){
        if (c == '\t' || c == '\n' || c == ' '){
            if (currentLength == 0){
                continue;
            }

            printf("Length of word %d: ||", currentIndex);

            for (int i = 0; i < currentLength; i++){
                putchar('-');
            }
            putchar('\n');

            currentLength = 0;
            ++currentIndex; 
        } else {
            ++currentLength;
        }   
    }

    return 0;
}

所以我可以编译它并使用 ./a.out 运行它,但是当我按“Enter”开始新的输入行('\n')时,它会运行 printf() 和 putchar() 函数( ' ' 或 '\t' 都不会触发输出)。 while 循环没有结束(它应该以 END-OF-FILE(CTRL-D) 结束),但我想知道为什么这些函数会在它们被调用时被调用。它可以防止一次输入多行。这是它的输出示例:

    how long are these words
    Length of word 0: ||---
    Length of word 1: ||----
    Length of word 2: ||---
    Length of word 3: ||-----
    Length of word 4: ||-----

为了清楚起见,我只在按“Enter”时从 printf() 和 putchar() 获得输出。 CTRL-D 只是结束循环和程序。

【问题讨论】:

  • 您使用的是 Windows 吗?它有不同的行尾。它使用\r\n
  • 不,我在 Ubuntu 16.04 上。

标签: c


【解决方案1】:

getchar() 默认情况下处于缓冲模式,因此在按下回车之前不会将字符提供给您的程序。此问题重复:How to avoid press enter with any getchar()

【讨论】:

    【解决方案2】:

    ENTER 释放缓冲区。

    在 ENTER 之前,您的代码无法使用数据。您的代码同时获取所有字符。

    操作系统负责维护缓冲区(您也许可以更改操作系统的这一方面)。

    【讨论】:

      【解决方案3】:

      在 c 中,任何输出(除非特别设置)都会被缓冲。

      在发生以下情况之一之前不会输出任何内容:

      1. fflush() 被称为
      2. 输出一个“\n”
      3. 缓冲区已满。

      这样您就可以在调用printf() 之后添加对flush() 的调用

      注意:除了制表符、空格、换行符之外,您可能还应该寻找其他单词分隔符。

      建议添加:单引号、双引号、句号、冒号、分号、左括号、左括号、右括号、右括号、反引号。

      【讨论】:

        猜你喜欢
        • 2021-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-05
        • 2016-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多