if the user entered a char instead of an int an error will be set on the stream so you might need to reset the stream
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int getPos()
{
int value;
std::cin>>value;
while(value<1 || value>8 || !std::cin)
{
if(!std::cin) ///user entered a character e.5 'a' instead of an int
{
std::cin.clear();
std::cin.ignore(1000,'\n');
}
std::cout<<"out of range \\ invalid input retry: ";
std::cin>>value;
}
return value;
}
I'm looking at making my default in my switch loop round to bring back the menu// or just allow the user to enter a value(1-5).
i'd like to see your code for this but i'd suggest you make sure that, only correct input gets it way to your switch, that way you might avoid the "need to bring up the menu again"
For the most part I agree with Yolanda, but I would do two things different.
1. In the while condition I would use:((value < 1 || value > 8) && !std::cin). When using '!' in a condition && tends to work better. I also added a set of () around the lhs which may or mat not be needed.
2. When using "std::cin.ignore(...)" I like to use this version:
@Andy hello while condition I would use:((value < 1 || value > 8) && !std::cin). When using '!' in a condition && tends to work better.
please note: the condition ((value < 1 || value > 8) && !std::cin) will not work properly , i mean
the function will never enter the loop if value<1 or value>8, the function will just return even if value == 20,-1,-19, check the condition's truth table.
what he/she needs is ((value < 1 || value > 8) || !std::cin)
I want to point out that this is a perfect example of a loop with the exit condition in the middle. Don't be afraid to code it this way. Here is JLBorges's excellent recursive solution recoded as a loop to demonstrate:
// avoid magic numbers
constint MINV = 1 ;
constint MAXV = 8 ;
int pos ;
while (true) { // loop exits from break below
std::cout << "enter position [" << MINV << '-' << MAXV << "]: " ;
if( std::cin >> pos ) { // if the user entered an integer
if( pos >= MINV && pos <= MAXV ) break ; // return valid value, within range
else std::cout << "value is out of range. try again\n";
} else { // user did not enter an integer. input failed
std::cout << "non-numeric input. try again\n";
std::cin.clear(); // clear the failed state of std:cin
std::cin.ignore( 1000,'\n' ); // and throw the bad input away
}
}
// pos is now a valid number
@Andy, I will have to work something up and give it a try with all
as for me well, when working with logic operators, if i find the result to an operation confusing then i like boiling everything down to a simple truth table,
that way what was confusing becomes obvious.
its good that we are always learning here, seeing different approaches to stuff its great, @JLBorges n @DHyden great approaches there.