Baruntar Baruntar - 1 year ago 178
C++ Question

Read a string of length greater than 4096 bytes from stdin in C++

I am trying to read in a string of length in 10^5 order. I get incorrect string if the size of string grows beyond 4096.
I am using the following code

string a;

This didn't work then I tried reading character by character by following code

unsigned char c;
vector<unsigned char> a;
c = getchar();

I have done necessary escaping for using
this also had the 4096 bytes problem. Can someone suggest a workaround or point to correct way of reading it.

Answer Source

Using this test-program based on what you posted:

#include <iostream>
#include <string>

int main()
    std::string a;

    std::cin >> a;

    std::cout << a.length() << std::endl;

I can do:

./a.out < fact100000.txt

and get the output:


However, if I copy'n'paste from an editor to the console, it stops at 4095. I expect that's a limit somewhere in the consoles copy'n'paste handling. The easy solution to that is of course to not use copy'n'paste, but redirect from a file. On some other systems, the restruction to 4KB of input may of course reside somewhere else. (Note that, at least on my system, I can happily copy and paste the 450KB of factorial result to another editor window, so in my system it's simply the console buffer that is the problem).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download