C++ Cin输入数字时 输入字母 Cin状态出错

来源:互联网 发布:交换机端口坏了怎么修 编辑:程序博客网 时间:2024/05/19 07:08

在做某个小程序时有一个判断输入数字的需求

当时我是这么写的

int num = -1;//input the total num of XXX cout << "Please input the num of XXX :    ";cin >> num;while  (num <= 0){cout << "\nPlease input the num of XXX:    ";cin >> num;}




情况就是while里面的cin不起作用了。Debug查看num的值一直是-1.地址也没变,cin也一直被触发。所以做的关于变量变化的猜测都推翻了。

那么情况就是cin本身出了问题。

首先参考老司机的方案,linux程序员常用的方法通过字符串输入变量然后转成int。这个方法还是成功解决了问题。

string strNum;//input the total num of XXXcout << "Please input the num of XXX :    ";cin >> strNum;int num = atoi(strNum.c_str());while (num <= 0){cout << "\nPlease input the num of Fingo parts :    ";cin >> strNum;num = atoi(strNum.c_str());}


但是一个老司机继续分析,应该是cin往int型输入char时导致cin状态出错导致EOF没有读取到。需要重新恢复一下cin的状态才能继续输入。

于是调整代码。用cin.fail()来判断状态,再用cin.clear()和cin.sync()来恢复cin的状态。

int num = -1;cin >> num;while (num <= 0){if (cin.fail()){cin.clear();cin.sync();}cout << "\nPlease input the num of XXX :    ";cin >> num;}

这样就解决了遇到的死循环的问题。


转载时请保留作者名字吧。

0 0