while 循环和 getchar() - 大输入

while loop and getchar() - large input

以下代码不允许我输入超过 4095 个字符的任何内容,除非我输入 \n,我想知道为什么会这样。

#include <stdio.h>

int main(void)
{
    int c;
    unsigned long long a = 0;

    while ((c = getchar()) != EOF)
        ++a;
    printf("\n%llu\n", a);

    return 0;
}

例如:

input: '#' * 4094

output: 4094

input: '#' * 4095 

output: 4095

input: '#' * 4096

output: 4095

等等...

但如果我输入 \n,我将能够循环更多的 4095 个字符等等...

input: ('#' * 4096) + '\n' + '#'

output: 4097

input: ('#' * 99999) + '\n' + ('#' * 99999)

output: 8191

正如 this answer on another Stack Exchange site 所解释的,您在这里看到的是操作系统键盘输入处理(“终端驱动程序”)的限制。

如果您将数据放入文件中,并且 运行 您的程序带有输入重定向,如下所示:

myprogram < input.txt

那么你应该能够真正阅读和计算任意长行。

还有其他方法可以绕过终端驱动程序的线路限制,如 the other question 所述。