gpt4 book ai didi

c++ - 重置流的状态

转载 作者:可可西里 更新时间:2023-11-01 18:19:03 25 4
gpt4 key购买 nike

我有一个问题与 stackoverflow 上的这个问题有点相似 std::cin.clear() fails to restore input stream in a good state ,但那里提供的答案对我不起作用。

问题是:如何将流的状态再次重置为“良好”?

这是我的代码,我是如何尝试的,但状态再也没有设置为好。我分别使用了这两行忽略。

int _tmain(int argc, _TCHAR* argv[])
{
int result;
while ( std::cin.good() )
{
std::cout << "Choose a number: ";
std::cin >> result;

// Check if input is valid
if (std::cin.bad())
{
throw std::runtime_error("IO stream corrupted");
}
else if (std::cin.fail())
{
std::cerr << "Invalid input: input must be a number." << std::endl;
std::cin.clear(std::istream::failbit);
std::cin.ignore();
std::cin.ignore(INT_MAX,'\n');
continue;
}
else
{
std::cout << "You input the number: " << result << std::endl;
}
}
return 0;
}

最佳答案

这里是代码

std::cin.clear(std::istream::failbit);

实际上并没有清除故障位,它替换流的当前状态为故障位

要清除所有位,只需调用 clear()


标准中的描述有点绕,声明为其他函数的结果

void clear(iostate state = goodbit);

Postcondition: If rdbuf()!=0 then state == rdstate(); otherwise rdstate()==(state | ios_base::badbit).

这基本上意味着下一次调用 rdstate() 将返回传递给 clear() 的值。除非有一些其他问题,在这种情况下你也可能会得到一个 badbit

此外,goodbit 实际上根本不是一个位,但其值为零以清除所有其他位。

要清除只是一个特定位,您可以使用此调用

cin.clear(cin.rdstate() & ~ios::failbit);

但是,如果您清除一个标志而其他标志仍然存在,您仍然无法从流中读取。所以这种用途是相当有限的。

关于c++ - 重置流的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11246960/

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