使用stringstream解析ifstream的问题

问题描述 投票:1回答:1

我有一个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();

FYI:enter image description here

c++
1个回答
0
投票

您需要致电clear()

[读入ss >> width >> height;之后,您已经读取了字符串流中的所有内容,因此设置了eofbit并翻转了failbit

[再次填充字符串流后,需要将failbit翻转回false,以使该流知道再次读取是好的:

ss.str(string());
ss.clear()
ss << line2; // After this line, why does `ss` is empty instead of holding `32768` ? 
fr.close();
© www.soinside.com 2019 - 2024. All rights reserved.