while 循环和 getchar() - 大输入

问题描述

以下代码不允许我输入超过 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 所述。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...