stopping multiple assignments

I have the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  char hit;   // taking char insted of int because it will get compiler to else statement when somebody types a character
round:// round starts here
{
cin>>hit;      
if(hit=='1')
{
hit=10;
}                       
else if(hit=='2')
{
hit=5;
}
else if(hit=='3')
{
hit=7;
}
else if(hit=='4')
{
hit=12;
}
else
{
cout<<"invalid move... try again";

goto round;
}
} // round ends here


the code runs fine but when i type combinations of keys (like 12,23;1234 etc..) the program changes the value of hitto the sum of all the hit conditions.. like if i type "12" the hit gets assigned to 15..... i want the user to have just one hit per move......

please help
Make hit an int and use cin.fail() to check if the player entered or not a valid value
1
2
3
4
5
6
7
int hit;
cin>>hit;
if(cin.fail())   //if a letter or invalid character was entered instead of a number
{
cout<<"Error:Invalid value entered!"<<endl;//then post a message
goto round;//and go back to the begining
}
but i also have to use character values later.....
what do you mean by 'later'?
You can't push '12' into a char. You could read into a std::string
http://www.cplusplus.com/reference/string/string/getline/
and do your comparisons using:
http://www.cplusplus.com/reference/string/string/compare/
Last edited on
Topic archived. No new replies allowed.