Search code examples
cloopswhile-looplinegetchar

while loop and getchar() - large input


The following code does not allow me to input anything above 4095 characters unless i type \n, and i would like to know why it occurs.

#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;
}

E.g:

input: '#' * 4094

output: 4094

input: '#' * 4095 

output: 4095

input: '#' * 4096

output: 4095

and so on...

but if i type \n, i will be able to loop more 4095 characters and so on...

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

output: 4097

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

output: 8191

Solution

  • As this answer on another Stack Exchange site explains, what you're seeing here is a limitation of your operating system's keyboard input handling ("terminal driver").

    If you put your data into a file, and run your program with input redirection, like this:

    myprogram < input.txt
    

    then you should be able to read and count truly arbitrarily long lines.

    There are other ways to get around the terminal driver's line restrictions, as explained at the other question.