简体   繁体   中英

Can't read in a long cin input to a string

I have code that looks like this

string inputString;
std::getline (std::cin, inputString)
cout << inputString;

when I cin a long string ~30k characters then inputString only has part of that string. Any ideas how to fix this?

From the std::getline() documentation on cppreference.com :

getline reads characters from an input stream and places them into a string:

1. Behaves as UnformattedInputFunction , except that input.gcount() is not affected. After constructing and checking the sentry object, performs the following:

  1. Calls str.erase()

  2. Extracts characters from input and appends them to str until one of the following occurs (checked in the order listed)

    a. end-of-file condition on input , in which case, getline sets eofbit .

    b. the next available input character is delim , as tested by Traits::eq(c, delim) , in which case the delimiter character is extracted from input , but is not appended to str .

    c. str.max_size() characters have been stored, in which case getline sets failbit and returns .

  3. If no characters were extracted for whatever reason (not even the discarded delimiter), getline sets failbit and returns.

2. Same as getline(input, str, input.widen('\\n')) , that is, the default delimiter is the endline character.

So check to see if your input is being limited by the value of inputString.max_size() . It might be near 32k on your system.

By default, the terminal works in canonical mode, and it has a buffer of the length 4096 Bytes. So that's why the maximum input that the string can take is 4095. Now the solution is to change to the noncanonical mode in Linux. You can do so by

$ stty -icanon # for switching to the noncanonical mode.
$ stty icanon  # reverting back to the canonical mode when you are done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM