【问题标题】:while loop and getchar() - large inputwhile 循环和 getchar() - 大输入
【发布时间】:2021-02-23 12:29:52
【问题描述】:

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

#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

【问题讨论】:

标签: c loops while-loop line getchar


【解决方案1】:

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

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

myprogram < input.txt

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

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

【讨论】:

    猜你喜欢
    • 2015-06-04
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多