2015-07-19 41 views
0

我有这样的代码,关于stringstream。我发现了一个奇怪的现象:为什么stringstream有这种行为?

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

假设我有FILE.TXT作为

4 5 

0 2 

在第一行第二行5后回报和2。该计划给了我:

4 5 

4 5 

这意味着pq分配不正确。但我检查了每次sstr.str()与获得正确的线的字符串。

为什么stringstream有这样的行为?

+0

什么是预期的输出呢? – Shoe

+1

[如何清除stringstream?](http://stackoverflow.com/questions/2848087/how-to-clear-stringstream)解决你的问题? – Lithis

回答

3

读取第二个整数后,流处于非良好状态,因此您必须在恢复之前重置其错误状态。

你真正的错误是不检查输入操作的返回值,或者你立刻就会发现这个错误!


更简单的解决方案可能是不尝试重用相同的流,而是让它重新每轮:

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

[Demo](https://ideone.com/piHs07)。 –

1

当你阅读p,然后q,到达后,你的流和国旗eofbit已设置,你不能再做任何事情。 只需clear()它和您的代码将按预期工作。

但是你可能需要使用直接file,而是和file.close();将有中更好的地方您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(); 
} 
0

您的代码具有一定的冗余线路:fstream可以在定义的过程中被打开,没有明确的文件需要close(),因为它在main()结束时自动销毁。

此外,在文件读取循环,行:sstr.str("");冗余以及:sstr << str应与stringstream sstr(line);,如果你想初始化每行一个新的stringstream,这将使线路取代。

应用上述更正,这里是你的代码:

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

注:该生产线while (sstr >> p >> q)假定一个行只包含整数,用空格分隔。

相关问题