如何检测控制台输入不是C++中的数字

How to detect that a console input is not a number in C++?

本文关键字:C++ 数字 输入 控制台 何检测 检测      更新时间:2023-10-16

这是代码...

#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;
}