gpt4 book ai didi

c++ - getline() 在读取最后一行后抛出 basic_ios::clear 异常

转载 作者:太空狗 更新时间:2023-10-29 20:54:03 25 4
gpt4 key购买 nike

我正在使用 qteSTLib、C++(clang LLVM 8.0 版)编写文件读取单元测试。我有以下逐行读取文件的代码。

std::ifstream infile;

try {
infile.open(path.c_str());
std::ios_base::iostate exceptionMask = infile.exceptions() | std::ios::failbit;
infile.exceptions(exceptionMask);

} catch (std::ios_base::failure& e) {
// print the exception
qDebug() << "Exception caught: " << QString::fromStdString(e.what());
}

try {
std::string line;
while (std::getline(infile, line)) {
// print the line
qDebug() << QString::fromStdString(line);
}

} catch (std::ios_base::failure& e) {
qDebug() << "Exception caught: " << QString::fromStdString(e.what());
}

问题:

上面的代码读取文件中的所有行并打印出来。但是在打印最后一行之后,它抛出异常并打印以下内容,

Exception caught: "basic_ios::clear"

我关注了很多线程,但找不到解决方案。为什么会出现此错误?

最佳答案

在您读取并打印所有行后,while (std::getline(infile, line)) 仍会尝试读取另一行。如果它完全失败——读取零个字符——它会设置failbit 来表示它的失败。

错误消息的奇怪部分是,尽管它的名称是 basic_ios::clear ,但它可用于设置失败位,如果您启用了相同的位,也会抛出异常异常

关于c++ - getline() 在读取最后一行后抛出 basic_ios::clear 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40561482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com