c++ - 使用 stringstream 解析 ifstream 的问题

标签 c++

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

仅供引用:enter image description here

最佳答案

你需要调用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/

相关文章:

c++如何将数组导出到excel

c++ - std::is_class 的实现

c++ - 将字符串传递给接受指向 char 的指针的函数

c++ - 在 C++ 中检查空文件

android - 通过 MoSync 进行 android c++ 软件开发是否值得?

c# - 在 SerialPort 上设置 DTR、RTS、CTS、DSR 和 Xonn/Xoff

c++ - WcfSvcHost 和 IIS WCF 主机遇到 BadImageFormatException

C++ 多个运算符 : assign A or B not equal to C

c++ - 为什么使用 'int' 数据类型而不是 'float' 数据类型?

c++ - C++ 中的未知属性 `extern_c` 警告