Why stringstream has this behavior?

谁说胖子不能爱 提交于 2020-01-17 05:32:09

问题


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?


回答1:


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



回答2:


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();
}



回答3:


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.



来源:https://stackoverflow.com/questions/31506146/why-stringstream-has-this-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!