#include <iostream>
int get_positive_integer()
{
int number ;
std::cout << "enter a positive integer: " ;
if( std::cin >> number ) // if the user entered a number
{
if( number > 0 ) return number ; // positive value, return it
else std::cout << "that is not a positive value. try again.\n" ; // number, but non-positive
}
else // the input is non-numeric
{
std::cout << "please enter a number. try again.\n" ;
std::cin.clear() ; // clear the failed state of the input stream
std::cin.ignore( 1000, '\n' ) ; // remove the bad input from the input buffer
}
return get_positive_integer() ; // try again
}
int main()
{
constint n = get_positive_integer() ;
std::cout << "\nyou entered " << n << '\n' ;
}
Also, the usual idea is to write pseudo code first, then turn that into real code.
One can write pseudo code by putting down general ideas of what needs to be done, as comments in the code. Keep going back, put in more detail, until you are happy to convert to real code.