4

I want to read a line from stdin and tokenize it by whitespace, using the istringstream class. But it doesn't work as expected:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    string input_line;
    istringstream input_stream;
    string word;

    cout << "> ";
    getline(cin, input_line);
    input_stream.str(input_line);
    input_stream >> word;
    cout << "  line:   " << input_line << endl;
    cout << "  stream: " << input_stream.str() << endl;
    cout << "  word:   " << word << endl;

    cout << "> ";
    getline(cin, input_line);
    input_stream.str(input_line);
    input_stream >> word;
    cout << "  line:   " << input_line << endl;
    cout << "  stream: " << input_stream.str() << endl;
    cout << "  word:   " << word << endl;
}

If I enter whitespace separated lines, all is fine:

> aa bb
  line:   aa bb
  stream: aa bb
  word:   aa
> xx yy
  line:   xx yy
  stream: xx yy
  word:   xx

However, if I enter lines without whitespace, strangely the >> operator correctly reads from the stream the first time, but not the second time:

> aa
  line:   aa
  stream: aa
  word:   aa
> xx
  line:   xx
  stream: xx
  word:   aa

What am I doing wrong?

Georg P.
  • 2,785
  • 2
  • 27
  • 53
  • 6
    The first `operator>>` reaches "end of file" and sets the stream's status accordingly. `str()` does not reset it. Invoke `clear()` explicitly to clear the stream status. – Sam Varshavchik Sep 05 '16 at 17:09
  • Or use it in a loop, and reconstruct the stream each time: `while (getline(can, input_line) { std::istringstream input_stream(input_line); ... }` – Pete Becker Sep 05 '16 at 17:16
  • 2
    @SamVarshavchik: Please use the **answer section** for posting your answers. You should know this by now. – Lightness Races in Orbit Sep 05 '16 at 17:39
  • Thanks for help. Sorry for the duplicate, but these kind of problems are not easy to find in all the answers about io-streams - I was searching a lot! – Georg P. Sep 05 '16 at 18:21

0 Answers0