Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read standard input into std::stringstream until Ctrl-D (end of transmission)?

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);     
like image 423
Char Avatar asked Oct 22 '25 03:10

Char


2 Answers

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();
like image 84
Zereges Avatar answered Oct 23 '25 18:10

Zereges


This is working for me:

string std_input;
stringstream stream;
while (getline(cin, std_input)) {
  stream << std_intput << endl;
}
like image 20
cbuchart Avatar answered Oct 23 '25 16:10

cbuchart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!