c++ - 为什么我必须将错误状态标志设置为 goodbit 才能使其工作?

标签 c++

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::ofstream os("test.txt");
    std::ifstream is("test.txt");
    std::string value("0");

    os << "Hello";
    is >> value;

    std::cout << "Result before tie(): \"" << value << "\"\n";
    is.clear();
    is.tie(&os);

    is >> value;

    std::cout << "Result after tie(): \"" << value << "\"\n";
}

上面的代码有输出:

Result before tie(): "0"
Result after tie(): "Hello"

但是没有 clear() 调用,value 保持为“0”——为什么?为什么我必须将输入流的错误状态标志设置为 goodbit?

注意找不到文件,这是本意。

最佳答案

可能发生的情况是,当您从 is 读取 value 时,您到达了文件末尾。显然,该标志不会被 tie() 输出流清除。

如果 EOF 标志保持设置,则不会从流中读取额外的字符,因此尝试为 value 读取新值将失败。

关于c++ - 为什么我必须将错误状态标志设置为 goodbit 才能使其工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49949558/

相关文章:

c++ - 从原点找到最近的位置

c++ - "Almost default"C++ 中的复制构造函数(和赋值运算符)

c++ - vector 中这种删除方法有什么问题?

c++ - 将不同的模板化类存储在一个容器中,而不会丢失有关其类型的信息

c++ - 使用 Boost Program 选项读取相对文件路径

c++ - 为什么 catch block 不共享 try block 的范围?

c++ - std::ofstream 在 DLL 中的行为不同

c++ - Visual Studio 2005 中的 <regex> 在哪里?

c++ - 如何在 OpenGL 中叠加文本

C++ 类析构函数使用新值而不是实际值