如何脱离io的死循环?

jingyueid 2005-09-20 03:51:11
unsigned int i = 0;

do {
cin >> i;
cout << i;
} while ( i == 0 );

i为一个非零值,但只要输入是不合法的就进入死循环。

要怎么处理?才能保证i会接受一个合法的数字(不等于0),并且如果用户的输入不合法,会要求用户重新输入?
...全文
215 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
jingyueid 2005-09-20
  • 打赏
  • 举报
回复
非常感谢!

ios::clear
void clear( int nState = 0 );

Parameter

nState

If 0, all error bits are cleared; otherwise bits are set according to the following masks (ios enumerators) that can be combined using the bitwise OR ( | ) operator. The nState parameter must have one of the following values:

ios::goodbit No error condition (no bits set).


ios::eofbit End of file reached.


ios::failbit A possibly recoverable formatting or conversion error.


ios::badbit A severe I/O error.
Remarks

Sets or clears the error-state flags. The rdstate function can be used to read the current error state.




istream::ignore
istream& ignore( int nCount = 1, int delim = EOF );

Parameters

nCount

The maximum number of characters to extract.

delim

The delimiter character (defaults to EOF).

Remarks

Extracts and discards up to nCount characters. Extraction stops if the delimiter delim is extracted or the end of file is reached. If delim = EOF (the default), then only the end of file condition causes termination. The delimiter character is extracted.

istream Overview | Input Stream Classes
zhouhuahai 2005-09-20
  • 打赏
  • 举报
回复
#include <iostream>
using namespace std;

int main()
{
unsigned int i = 0;

do {
cin.clear();
cin.ignore();
cout << "input:";
cin >> i;
if(!i)
cout << "input error." << endl;
else
cout << i << endl;
} while (i == 0);

return 0;

}

在while里面加入
cin.clear();
cin.ignore();就不会死循环了.

jingyueid 2005-09-20
  • 打赏
  • 举报
回复
我在vc2003, gcc下都是死循环。

vc6是不是会自动将标准输入的缓冲区给清空了??
nasi00 2005-09-20
  • 打赏
  • 举报
回复
我的vc6并没有死循环阿,是不是得接着输入让你觉得像是死了?你看看键盘还能用么?

看到提示的话就重新输入:

#include <iostream>
using namespace std;

int main()
{
unsigned int i = 0;

do {
cout << "input:";
cin >> i;
if(!i)
cout << "input error." << endl;
else
cout << i << endl;
} while (i == 0);

return 0;

}
jingyueid 2005-09-20
  • 打赏
  • 举报
回复
在线等,立结!

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧