0

This program reads the first line over and over again. Everywhere I have looked for answers I have learned that it should read the next line after hitting "Enter". Why doesn't it?

#include<iostream>
#include<sstream>

using namespace std;

int main() {
    stringstream ss;
    string line, str;

    while(getline(cin, line) ){
        ss.str(line);
        ss >> str;
        cout << str << endl;

        cout << endl;
    }
    return 0;
}

Output looks like this

Hello
Hello

World!
Hello

and
Hello

again
Hello


Hello


Hello
  • Did you forget to clear the stringstream? https://stackoverflow.com/questions/20731/how-do-you-clear-a-stringstream-variable – Eljay Feb 09 '19 at 19:02
  • When you read the last of `std::stringstream` content, `eof` flag is set on it. You have to clear flags before reusing stream with `clear()` method. – Yksisarvinen Feb 09 '19 at 19:06
  • Alternatively, create a new `istringstream` object inside the loop: `while (getline(cin, line)) { istringstream iss(line); iss >> str; cout << str << endl; cout << endl; }` – Remy Lebeau Feb 09 '19 at 22:33

0 Answers0