Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

user input handling 1

Status
Not open for further replies.

holidayIT

IS-IT--Management
Apr 2, 2004
138
US
i may have a very simple question, please forgive me if this is a newbie question.

i have a menu that uses an int that i cin and then uses a switch to determine the course of action. how can i prevent or handle the user entering a char? i already am using cin.good() to determine that they entered anything at all, but i need to make sure they are entering a valid int.

is there an easy way to do this?

this is a console app
 
When you enter a char, cin puts some very large negative number in the int, apparently some kind of error code. This means that all you have to do is make sure the int is between 1 and however many menu items you have, ie

int sel;
cin >> sel;
while(sel < 0 || sel > MENU_ITEM_COUNT)
{
cout << "Please enter a valid selection";
cin >> sel;
}

switch(sel)
{
// do stuff here
}
 
do you know of any way i can check just a variable that i store in a class if it is a double or not?
 
Q1. A classic way to process a switch statement is something like:

...
cout << your choices are: ... [whatever] << endl;

while ((choice = cin.get()) != EOF)
{
switch (choice)
{
case 'A': //do something when a is found
break;

case 22:
case 73: // do something when 22 or 73 is found
break;

case 'Z': // do something when Z is found
break;

default: cout << "hey dummy, enter a valid choice!"
}
}
...

Q2. to determine a var type, read up on <typeinfo>

gooooood luck,

norm



 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top