Corey Starbird
Corey Starbird

Reputation: 73

C++ Input validation to make sure a number was entered instead of a letter

So I'm trying to set this program up to calculate the balance of an account. I need to make sure the starting balance is entered as a positive number. I have the positive part down, but how do I make sure that the input is also a number and not letters or other non-numbers?

#include <iostream>
#include <cmath>
#include <iomanip>
#include <string>
using namespace std;

int main()
{

double  startBal,    // Starting balance of the savings account
        ratePercent, // Annual percentage interest rate on account
        rateAnnual,  // Annual decimal interest rate on account
        rateMonth,   // Monthly decimal interest rate on account
        deposit1,    // First month's deposits
        deposit2,    // Second month's deposits
        deposit3,    // Third month's deposits
        interest1,   // Interest earned after first month
        interest2,   // Interest earned after second month
        interest3,   // Interest earned after third month
        count;       // Count the iterations

// Get the starting balance for the account.
cout << "What is the starting balance of the account?" << endl;
cin >> startBal;
while (startBal < 0 ) {
    cout << "Input must be a positive number. Please enter a valid number." << endl;
    cin >> startBal;
}

// Get the annual percentage rate.
cout << "What is the annual interest rate in percentage form?" << endl;
cin >> ratePercent;

// Calculate the annual decimal rate for the account.
rateAnnual = ratePercent / 100;

// Calculate the monthly decimal rate for the account.
rateMonth = rateAnnual / 12;

while (count = 1; count <= 3; count++)
{

}

return 0;
}

Thanks!!!

Upvotes: 0

Views: 7484

Answers (3)

Murilo Vasconcelos
Murilo Vasconcelos

Reputation: 4827

You can verify if cin was successful:

double startBal;
while (!(std::cin >> startBal)) {
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
    std::cout << "Enter a valid number\n";
}

std::cout << startBal << endl;

Don't forget to #include <limits> to use std::numeric_limits<streamsize>::max().

Upvotes: 4

john
john

Reputation: 88027

What you're asking for is actually quite difficult. The only completely correct way is to read your input as a string, then see if the string is in the right format for a number, and only then convert the string to a number. I think that's quite difficult when you're just a beginner.

Upvotes: 0

nhgrif
nhgrif

Reputation: 62072

double x;
std::cout << "Enter a number: ";
std::cin >> x;
while(std::cin.fail())
{
    std::cin.clear();
    std::cin.ignore(numeric_limits<streamsize>::max(),'\n');
    std::cout << "Bad entry.  Enter a NUMBER: ";
    std::cin >> x;
}

Replace x and double with whatever variable name and type you need. And obviously, modify your prompts to whatever is necessary.

Upvotes: 1

Related Questions