在做某个小程序时有一个判断输入数字的需求
当时我是这么写的
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 XXX
cout << "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());
}