gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:49:00 27 4
gpt4 key购买 nike

#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/

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