简体   繁体   中英

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?

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";
}

When you read p , then q , you reach the end of your stream and the flag eofbit is set and you can't do anything anymore. Just clear() it and your code will work as you expect.

But you may want to use directly file instead, and file.close(); will have a better place within your if :

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

Your code has some redundant lines: fstream could be opened during the definition and no explicit file close() is needed, as it is automatically destroyed at the end of main() .

Additionally, in your file reading loop, the line: sstr << str should be replaced with stringstream sstr(line); if you want to initialize a new stringstream for each line, which will make the line: sstr.str(""); redundant as well.

Applying the above corrections, here is your code:

int main() {

   int p, q;
   fstream file("file.txt", ios::in);

   // check status
   if (!file) cerr << "Can't open input file!\n"; 

   string line;

   // read all the lines in the file
   while(getline(file, line)) {

       // initialize the stringstream with line
       stringstream sstr(line);

       // extract line contents (see Note)
       while (sstr >> p >> q) { 

           // print extracted integers to standard output
           cout <<"p: " << p <<" q: "<< q << endl;
       }
   }

   return 0;
}

Note: The line while (sstr >> p >> q) assumes that a line contains only integers, separated by white space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM