0

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

4

2 回答 2

1

std::endl输出\n并刷新流。然而,stringstream::flush()毫无意义,什么也不做。flush仅当底层缓冲区与终端等输出设备绑定时才有意义,但是,astringstream无处可刷新内容。如果要清除字符串流的内容,请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
}

Also, if you want to insert a newline into the stringstream, just do ss << '\n'; and do not call std::endl.

于 2012-09-22T07:21:41.413 回答
0

事实证明,结尾没有换行符ss。执行以下语句后:

getline(infile, str);
ss << str;

ss不会包含换行符,因为getline()不会在存储到第二个参数的字符串末尾添加换行符。结果,当这个语句被执行时:

ss.ignore(INT_MAX, '\n');

流失败,因为它到达流的末尾而没有找到要停止的换行符。


ss.ignore()ss.str()如果用于存储字符串, 则不需要,它会替换流的全部内容。如果流失败,则应将其重置并将其内容设置为空字符串""。或者,ss.ignore()可以使用,但只要在读取数据后立即将换行符插入流中,这样就不会导致流失败——但如果稍后设置流的内容,这将是多余的使用ss.str().

ss.clear()可以通过在为流分配文件下一行的内容之前调用来确保成功读取文件的下一行,因为流的旧内容会被覆盖ss.str()。流状态可以在循环开始时重置,即使流在循环后期失败也不会出现问题:

while(getline(inFile, str)) {
    ss.clear();   // make sure stream is good
    ss.str(str);  // overwrite contents of stream with str
    ss >> a >> b;
    // Even if the stream fails after this line, the stream is reset before each
    // line is stored into the stream, and no problems should occur while reading
    // and parsing subsequent lines in the file.

    // Code to validate and store data from file...
}
于 2012-09-22T05:36:56.377 回答