0

I need to read text from stdin that can be up to 1000 lines long, but potentially less. How can I get this input into one string?

string s;
string line;
while (cin) {
    getline(cin, line);
    s += line;
}

This runs forever and I can never use string s

  • Did you end your input stream? – tadman Apr 23 '21 at 00:43
  • This will run until it reaches an EOF. How else would you know when the input ends if not by some end marker? – Chris Dodd Apr 23 '21 at 00:44
  • What does "runs forever" means? – Sam Varshavchik Apr 23 '21 at 00:44
  • How can I test for EOF? – deepthought Apr 23 '21 at 00:46
  • Also how can I simulate EOF when entering strings on the terminal – deepthought Apr 23 '21 at 00:47
  • 1
    On Linux you can press Ctrl-D (Bash, zsh, ...). You should have the same behavior on MacOS and on Windows with Git Bash. You can use a code like `while (getline(cin, line)) {s += line;}`. The code from your question won't work correctly. It would read the last line twice. You can read https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons Here is an example: https://wandbox.org/permlink/vW4D4aRFXY1ahu10 – jabaa Apr 23 '21 at 00:54
  • Also if you're not expecting an empty line as part of your input, you can use that to break out of the while loop. Just check if line is an empty string and break or something to that effect. – Alex Riveron Apr 23 '21 at 01:09
  • This is a pretty inefficient way to build your string. Why not use the `rdbuf` method to read the entire input at once? Then, since you seem to want newlines removed, you can perform that operation in O(N) time afterwards. – paddy Apr 23 '21 at 01:30
  • In CMD it is Cntrl-Z ending copy con file.txt (haven't tested it on above loop) but I always assumed the EOF input convention in MS-DOS and Windows is Ctrl-Z. In above loop you actually test cin=null and I doubt that will ever come. – Goodies Apr 23 '21 at 01:34
  • Does this answer your question? [How to read until EOF from cin in C++](https://stackoverflow.com/questions/201992/how-to-read-until-eof-from-cin-in-c) – risingStark Apr 23 '21 at 01:35

0 Answers0