0

i have written simple code to calculate payroll, runs ok when i put right kind of input( related to what its asking for) but when i put any other input then it ignores all the other codes and gives random number as calculation and goes to end of the program. for eg. if i input alphabet instead of number in rate per hour or in hour worked....please help!!!

#include <iostream>
#include <string>

using namespace std;

double calPayroll(double rate, double hour);

int main()
{
    char option;
    string name;
    double rate,hour;

    cout << "Please enter employee full name: ";
    getline(cin,name);

    cout << "Please enter "<<name <<"  rate per hour: ";
    cin >> rate;
    cout << "Please enter total hour " <<name << " worked: ";
    cin >> hour;
    cout <<"\n\nSalary for " << name << " is: " << calPayroll(rate,hour)      <<endl <<endl;

    cout << "Next Payroll: Press any key to continue or 'n' to exit)\n\n";
    cin >> option;
    cout<< option;

system ("pause");
return 0;
}
de.sk
  • 79
  • 1
  • 7

2 Answers2

0

You should probably store your numbers as strings first, check if they are valid numbers and then convert them to doubles only if they are valid.

See this link for checking if a string is numeric: How to check if a string is a number?.

For the conversion you could use a function like atof().

Community
  • 1
  • 1
grae22
  • 104
  • 11
0

how do I validate user input as a double in C++? should be useful to you.

To validate numeric input you can check the return value of stream operator >>

if (cin >> rate) {
    // valid
}
else {
    // invalid
}
Community
  • 1
  • 1
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50