3

How do I take standard input of several lines and store it into a std::streamstring until the user presses Ctrl-D to signal end of input? I'd like to do something like this but for variable lines of input. How can I check for end of transmission signal as signaled by a Ctrl-D press by the user?

    string std_input;
    stringstream stream(std_input);
    while (getline(cin, std_input))
        stream(std_input);     
cbuchart
  • 10,847
  • 9
  • 53
  • 93
Char
  • 1,635
  • 7
  • 27
  • 38
  • 1
    [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) "Describe the problem. "It doesn't work" is not a problem statement. Tell us what the expected behavior should be. Tell us what the exact wording of the error message is, and which line of code is producing it. Put a brief summary of the problem in the title of your question." – Mooing Duck Apr 11 '17 at 23:20
  • Which part can I be more clear on. The program compiles and doesn't throw any error. I want to get variable user input from stdin and store it into a stream. I linked to an example of a similar question but I want to extend it for variable lines of input. – Char Apr 11 '17 at 23:35
  • 1
    You say you'd like to read in several lines from standard input and store it in a stringstream, then have code that answers your own question. What's the problem? What information do you need from us? – Mooing Duck Apr 11 '17 at 23:37

2 Answers2

6

Easiest way in my opinion is to pass underlaying buffer of std::cin to string stream, since it has overload for std::basic_streambuf

std::ostringstream sstream;
sstream << std::cin.rdbuf();
Zereges
  • 5,139
  • 1
  • 25
  • 49
3

This is working for me:

string std_input;
stringstream stream;
while (getline(cin, std_input)) {
  stream << std_intput << endl;
}
cbuchart
  • 10,847
  • 9
  • 53
  • 93
  • 1
    Recommend `'\n'` in place of `endl` off general principals. It's not going to matter much with a string stream, but should this code be ported to write file the flush built into in `endl` will hurt performance grievously. – user4581301 Apr 11 '17 at 23:42