Q:

Why stringstream has this behavior?

I have a code like this, concerning stringstream. I found a strange behavior:
#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

int main()
{
  int     p, q;
  fstream file;
  string  str;
  stringstream sstr;

  file.open("file.txt", ios::in);
  if(file.is_open()) {
    while(getline(file, str)) {
      sstr << str;
      sstr >> p >> q;
      cout << p << ' ' << q << endl;
      sstr.str("");
    }
  }
  file.close();

  return 0;
}

Suppose I have file.txt as
4 5

0 2

with return after 5 in the first line and 2 in the second line.  The program gives me:
4 5

4 5

which means p and q are not correctly assigned. But I checked that each time sstr.str() with get the correct string of the line.
Why stringstream has a behaviour like this?

A:

The stream is in a non-good state after reading the second integer, so you have to reset its error state before resuming.
Your real mistake was to not check the return value of the input operations, or you would have caught this immediately!

The simpler solution may be to not try to reuse the same stream, but instead make it anew each round:
for (std::string line; std::getline(file, line); )
{
    std::istringstream iss(line);
    if (!(iss >> p >> q >> std::ws) || !iss.eof())
    {
        // parse error!
        continue;
    }
    std::cout << "Input: [" << p << ", " << q << "]\n";
}

