如何检测控制台输入不是C++中的数字
How to detect that a console input is not a number in C++?
这是代码...
#include <iostream>
#include <iomanip>
#include <cmath>
#include <math.h>
using namespace std;
void CorrectPercent(double Percent) {
unsigned short int Error = 0;
while (Error==0){
cout << "nEnter the annual interest rate (%):tt";
cin >> Percent;
do {
if (Percent <= 0) {
cout << endl << "Please enter a valid annual interest rate (%): ";
cin >> Percent;
} else if (isnan(Percent) == true) {
cout << endl << "Please enter a valid annual interest rate (%): ";
cin >> Percent;
}
else {
Error=1;
}
} while (Error == 0);
//Error++;
}//while (Error == 0);
}
int main()
{
double Percent;
char Retry = 'Y';
do
{
cout << setprecision(2) << fixed;
system("cls");
CorrectPercent(Percent);
} while (Retry == 'Y' || Retry == 'y');
return 0;
}
CorrectPercent函数应该继续运行,直到输入有效的数值。 所以,问题是,如何检测输入是数字? 只是为了补充信息,我正在开发Visual Studio 2015。
由于Percent
被声明为double
,每当用户输入非数字数据时,cin >> Percent
都会失败。您可以使用以下方法检测到这一点cin.fail()
:
std::cin >> Percent;
while (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(std::max<std::streamsize>());
std::cout << "Please enter a valid number." << std::endl;
std::cin >> Percent;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 在将数字随机生成为数组期间从内存输出随机数的数组