我有一个txt文件,内容如下:
1
256 128
32768
我写了一段代码来解析这些数字。但是在ss << line2;
之后, 变量 ss
是空的。有人帮我解决这个问题吗?
ifstream fr;
fr.open(input);
if (!fr)
return false;
string line1;
string line2;
getline(fr, line1);
getline(fr, line1);
getline(fr, line2);
stringstream ss;
uint32_t width, height;
ss << line1;
ss >> width >> height;
ss.str(string());
ss << line2; // After this line, why does `ss` is empty instead of holding `32768` ?
fr.close();
最佳答案
你需要调用clear()
在您读入 ss >> width >> height;
后,您已经读取了字符串流中的所有内容,因此设置了 eofbit
并且 failbit
被翻转了。
再次填充字符串流后,需要将failbit
翻转回false,让流知道可以再次读取/写入:
ss.str(string());
ss.clear(); // Let the world know we're good again!
ss << line2; // ss.str() will now show that we have stuff!
关于c++ - 使用 stringstream 解析 ifstream 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59274151/