调用stringstream时,stringstream::ignore()似乎总是失败,即使在调用stringstream::clear()之后也是如此:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cassert>

using namespace std;

int main() {
    int a, b;
    stringstream ss;
    string str;
    ifstream inFile("file.txt");
    if(!inFile) {
        cerr << "Fatal: Cannot open input file." << endl;
        exit(1);
    }

    while(getline(inFile, str)) {
        ss << str;                // read string into ss
        ss >> a >> b;             // stream fails trying to store string into int

        ss.clear();               // reset stream state
        assert(ss.good());        // assertion succeeds

        ss.ignore(INT_MAX, '\n'); // ignore content to next newline
        assert(ss.good());        // assertion fails, why?
    }

    return 0;
}


file.txt包含以下文本:

123 abc
456 def


为什么在ss.good()之后ss.ignore()为假?

最佳答案

std::endl输出\n并刷新流。但是,stringstream::flush()是没有意义的,什么也不做。 flush仅在将底层缓冲区绑定到类似于终端的输出设备时才有意义,但是stringstream无处可将内容刷新到其中。如果要清除字符串流的内容,请执行ss.str("");。但是,我可能会将代码更改为以下内容:

while(getline(inFile, str)) {
    ss.str(str);              // call ss.str() to assign a new string to the stringstream
    if(!ss >> a >> b)         // check if stream fails trying to store string into int
    {
        ss.clear();           // Read failed, so reset stream state
    }
    else
    {
        // Read successful
    }
    // Do other stuff
}


另外,如果要在字符串流中插入换行符,只需执行ss << '\n';而不调用std::endl

关于c++ - stringstream::ignore(INT_MAX,'\n')导致流失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12541049/

10-13 08:29