I have two cin validation functions in a program I'm writing - one to validate int, and the other to validate double, whilst both ensuring that the user cannot enter char values. The problem I'm having is that sometimes the function will begin validation immediately after the user is asked to enter a value, like in this case:
cout << endl << "Enter transaction ID to edit : ";
toEdit = validateIntInput(toEdit, 1, MAX_TRANS);
Or this case:
cout << "How much are you adding? : " << char(156);
tVal = validateDoubleInput(tVal, 0.01, 999999998);
However, in other cases, the program will not tell the user that their input is invalid, and simply create a new line, like in this case:
cout << "What day of the month is the bill normally paid? (1 - 31) (You can change this later) : ";
paymentDay = validateIntInput(paymentDay, 1, 31);
Or this case:
cout << "Annual interest rate (%) : ";
annualInterestRate = validateDoubleInput(annualInterestRate, 0.01, 100);
The code for validateIntInput
is:
int validateIntInput(int paramToCheck, int minValue, int maxValue)
{
paramToCheck = 999999999;
string line;
while (getline(cin, line))
{
stringstream linestream(line);
linestream >> paramToCheck;
// if the first if is not included, the program will assume invalid input has been entered as soon as the user is asked for input
if (paramToCheck == 999999999)
{
cout << "";
paramToCheck = 0;
}
// if the input contains a string or is not within bounds, throw an error
else if (!linestream.eof() || paramToCheck < minValue || paramToCheck > maxValue)
{
cout << red << "Invalid input. Try again : " << white;
}
// if the input is valid, stop the loop and accept the input
else
{
break;
}
}
return paramToCheck;
}
And the code for validateDoubleInput
is:
double validateDoubleInput(double paramToCheck, double minValue, double maxValue)
{
paramToCheck = 999999999;
string line;
while (getline(cin, line))
{
stringstream linestream(line);
linestream >> paramToCheck;
// if the first if is not included, the program will assume invalid input has been entered as soon as the user is asked for input
if (paramToCheck == 999999999)
{
cout << "";
paramToCheck = 0;
}
// if the input contains a string or is not within bounds, throw an error
else if (!linestream.eof() || paramToCheck < minValue || paramToCheck > maxValue)
{
cout << red << "Invalid input. Try again : " << white;
}
// if the input is valid, stop the loop and accept the input
else
{
break;
}
}
return paramToCheck;
}
NOTE: The only reason why the functions assign a value of 999999999 to the parameter and check for this on startup is because the program sometimes threw an exception even before the user had entered anything.
I really have no idea what could be going wrong here - could anyone help me get to the bottom of the problem?
Thanks in advance to anyone who can!