重置流的状态
Resetting the State of a Stream
本文关键字:状态 更新时间:2023-10-16
>我有一个问题,与堆栈溢出 std::cin.clear() 上的问题略有相似,无法恢复处于良好状态的输入流,但那里提供的答案对我不起作用。
问题是:如何再次将流的状态重置为"良好"?
这是我的代码,我如何尝试它,但状态永远不会再设置为好。我分别使用了两行忽略。
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);
实际上并没有清除故障位,它会用failbit
替换流的当前状态。
要清除所有位,只需调用 clear()
。
标准中的描述有点复杂,说明为其他功能的结果
void clear(iostate state = goodbit);
后置条件:如果
rdbuf()!=0
则state == rdstate();
否则rdstate()==(state | ios_base::badbit)
。
这基本上意味着下一次调用rdstate()
将返回传递给clear()
的值。除非存在其他问题,在这种情况下,您也可能会得到badbit
。
此外,goodbit
实际上根本不是位,但值为零以清除所有其他位。
要仅清除一个特定位,您可以使用此调用
cin.clear(cin.rdstate() & ~ios::failbit);
但是,如果清除一个标志而其他标志仍然存在,则仍然无法从流中读取。所以这种使用是相当有限的。
相关文章:
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- OSX MetalKit CVMetalTextureCacheCreateTextureFromImage失败,状态:
- std::future_error:无关联状态
- 如何避免LED在循环状态变化中闪烁?
- boost 是否有按特殊类型值编码状态"compact optional"?
- 为什么系统函数总是在C++中返回已转移的退出状态?
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 当可输入框在窗口中处于活动状态时获得通知的任何方法
- 检查两个节点在子节点上是否具有相同状态的更优雅的方法
- 将有状态的 lambda 传递到 C 样式函数中,而无需上下文参数
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 编译问题:在函数"_start"中:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- C++部分概念 id:显式模板规范顺序/第一个参数的特殊状态的原因是什么?
- 试图在崇高中奔跑. 错误 已发生: 收集2.exe: 错误: ld 返回 1 退出状态
- 在容器上移动分配:以前包含的对象的状态
- collect2:错误:ld 返回 1 个退出状态未定义的引用
- 具有动态大小的特征矩阵的默认初始状态
- 如何从Clojure调用C++程序,以使程序保持打开状态?
- q网络回复 无状态码或错误,但失败