I am new in C++ and I have an assignment to make a calculator. My teacher wants to have a validation every time that the user entered wrong. For example, it asks for a number and when the user enters a number it should re-prompt the user to enter again until correct. But I have this problem that when I enter a number and there is a letter on it, it does not validate right. Example inputs: 234ea1234, 4e14, ew2314. Can someone help me on how to make the correct code on how to do this. How can I re-prompt to ask the user again for every wrong answer.
#include <iostream>
#include <cctype>
int get_int( constchar* prompt )
{
if(prompt) std::cout << prompt ;
std::cout << ": " ;
int number ;
// if the user entered a valid integer and the next char entered is a white space
// https://en.cppreference.com/w/cpp/io/basic_istream/peek
// https://en.cppreference.com/w/cpp/string/byte/isspaceif( std::cin >> number && std::isspace( std::cin.peek() ) )
return number ; // return the integer
// if we reach here, the return was not executed; input failed
// handle the error and retry
// https://en.cppreference.com/w/cpp/io/basic_ios/clear
std::cin.clear() ; // clear a possible failed state of stdin
// extract and discard the bad input line
// https://en.cppreference.com/w/cpp/io/basic_istream/ignore
std::cin.ignore( 1000, '\n' ) ;
// inform the user and try again
std::cout << "bad input. try again\n" ;
return get_int(prompt) ;
}int main()
{
constint a = get_int( "enter an integer" ) ;
constint b = get_int( "enter another integer" ) ;
if( b != 0 ) std::cout << a << " / " << b << " == " << double(a) / b << '\n' ;
else std::cout << "division by zern" ;
}