gpt4 book ai didi

c++ - 数据错误,重试

转载 作者:行者123 更新时间:2023-11-30 00:36:32 28 4
gpt4 key购买 nike

我在一本书中找到了这段代码片段:

int ival;
// read cin and test only for EOF; loop is executed even if there are other IO failures
while (cin >> ival, !cin.eof()) {
if (cin.bad()) // input stream is corrupted; bail out
throw runtime_error("IO stream corrupted");
if (cin.fail()) { // bad input
cerr<< "bad data, try again"; // warn the user
cin.clear(istream::failbit); // reset the stream
istream::iostate cin_state = cin.rdstate();
continue; // get next input
}
// ok to process ival
}

如果我在命令窗口中点击'f',就会出现无数“坏数据,重试”,cin_state为0X02,等于badbit。 Failbit一直没有搞清楚,为什么?

最佳答案

问题是 f 永远不会从输入流中删除,所以 cin >> ival 不断尝试一遍又一遍地读取它。

你需要跳过它。参见,例如,How does istream::ignore( ) work?

关于c++ - 数据错误,重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15830097/

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