I am trying to validate the length entered by a user. However, as I enter random values when testing the code below it continues to my next statement if I enter 1asdsa for the value of length.
cout << "\nRectangular Pool" << endl << endl;
cout << "Please input the length of the desired pool (rounding up to the nearest half foot, ex: 11.5): ";
cin >> length;
// Legth Input Validation
while (length < 1 || cin.fail())
{
cin.clear();
cin.ignore(INT_MAX, '\n');
cout << "\nYour have enter an invalid leght! Please try again! " << endl;
cout << "Please input the length of the desired pool (rounding up to the nearest half foot, ex: 11.5): ";
cin >> length;
}
#include <iostream>
#include <cctype>
#include <cmath>
double get_length()
{
std::cout << "length of the desired pool (a value not less than 1): " ;
double length ;
if( std::cin >> length ) // if the user entered a number
{
// find out (peek) what the next input character is
constauto next = std::cin.peek() ;
// if it is not a white space, the input is invalid eg. 1asdsa
if( !std::isspace( static_cast<unsignedint>(next) ) )
std::cout << "invalid input, a bad character immediately after the number" ;
// if the length entered is less than one, the input is invalid
elseif( length < 1.0 ) std::cout << "invalid input, the length can't be less than one" ;
else // if we reach here, we got a positive length
return std::round(length*2) / 2.0 ; // round length to the nearest half-foot and return it
}
else std::cout << "invalid input, not a number" ; // a non-number was entered
// if we reach here, the input was invalid (return was not executed)
std::cin.clear() ; // clear a possible failed state of the stream
std::cin.ignore( 1'000, '\n' ) ; // throw the rest of the bad input line away
std::cout << ". try again.\n" ;
return get_length() ; // try again
}
int main()
{
const auto len = get_length() ;
std::cout << len << '\n' ;
}