通过字符串流更新 int

Updating int through stringstreams

本文关键字:更新 int 字符串      更新时间:2023-10-16

我试图从文件中逐行读取一对值,但整数ij没有更新。我的ij分配错了吗?我已经找到了一种让代码工作的方法,但我很好奇为什么第一个 while 循环不起作用。

控制台输出:

127 86
127 86
141 127
127 86
153 127
127 86
165 127
127 86
171 127
127 86
174 127
127 86
191 27
127 86
191 87
127 86
191 99
127 86
191 102
127 86

女工程师:

#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
void test()
{
    ifstream inputfile;
    inputfile.open("test.txt");
    string line;
    stringstream lineS;
    int i, j;
    while ( getline( inputfile, line ) )
    {
        lineS.str(line);
        cout << lineS.str() << endl;
        lineS >> i >> j;
        cout << i << " " << j << endl << endl;
    }
    /* This works
    while (!inputfile.eof()) {
        inputfile >> i >> j;
        cout << i << " " << j << endl << endl;
    }*/
    inputfile.close();
}
int main()
{
    test();
    return 0;
}

这是文本文件测试.txt:

127 86
141 127
153 127
165 127
171 127
174 127
191 27
191 87
191 99
191 102

问题似乎是,当您从lineS读取一次时,会设置eofbit标志,并且在重置字符串时不会清除它。要么是这样,要么是标准库代码中存在错误,当您重置字符串时,该错误无法正确重置读取位置。

两种解决方案:每个循环手动清除流状态,或在循环内定义lineS

您尚未重置流的指向字符串开头的 get 指针。更改基础字符串并不重要。

更好的习语是在循环中构造字符串流:

while ( getline( inputfile, line ) )
{
  istringstream lineS( line );
  lineS >> i >> j >> ws;
  if (!lineS.eof()) inputfile.setstate( ios::failbit );
}

另请注意,任何输入错误都会被识别并传播回原始输入流。

希望这有帮助。