-1

This is the code...

#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 (%):\t\t";
    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;
}

The CorrectPercent function is supposed to keep running until a valid numeric value is entered. So, the question is, how can I detect that the input is numeric? Just for additional info, I'm working on Visual Studio 2015.

1 Answers1

-3

Since Percent is declared as a double, cin >> Percent will fail whenever the user enters non-numerical data. You can detect this with 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;
}
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268