Hello, i recently learned about switch statements, do loops, if then statements and i tried to write my own mini candy and maturity checker. however i was randomly testing for invalid answers and when i input "yes" for the first prompt (candy on a scale) it validates it as 5+ AND it also automatically validates as 13+ for the next question without even giving me an option to answer. also i only am using systempause temporarily since i dont know how to use the other ways properly. thanks.
#include <iostream>
usingnamespace std;
int main()
{
int candy;
int age;
cout << "Game time. \nMini Personality Check.\nDo you enjoy candy?\n\nRate it on a scale from 1-10: (1-10)\n\n"; // look what happens if you type "yes" here
cin >> candy;
if (candy >= 5)
{
cout << "\nAwesome.\n\nHow old are you?: ";
cin >> age;
if (age >= 13) // but i can put something like "yes" and it will execute this statement
{
cout << "\nOkay good. Old enough. So you're a mature person who enjoys candy.\n";
}
elseif (age <= 13)
{
cout << "\nSo you're a young person who enjoys candy. \n";
}
else
{ cout << "Invalid answer.\n";
}
}
elseif (candy <=5)
{
cout << "\nOkay. How old are you?: \n\n";
cin >> age;
if (age >=13)
{
cout << "\nAlright so you're mature but you don't enjoy candy.\n";
}
elseif (age <=13)
{
cout << "\nYoung person and you don't enjoy candy? Strange.\n";
}
else
{
cout << "Invalid answer.\n";
}
}
else
{
cout << "invalid answer.\n";
}
system ("PAUSE");
}
> why is "yes" a valid answer to an integer prompt
It is not. The reading failed as well as the next readings, because the streams remains in an invalid state.
¿what did you expect to happen?
Variables candy and age were not initialized. Entering "yes" you generated std::cin error. So nothing was enetered and arbitrary values of candy and age were used.
thanks, however what if this was part of a real game and it prompted you with these questions. how do real games prevent invalid answers like "yes" to integers from doing this stuff like say if someone wants to just mess around and puts a word for a numerical question. how does one stop the program from generating an error in a real game and instead putting something like "try again" or maybe not even allowing characters to be used?
I/O is not as simple as people think. You must spend a lot of time making sure that the user gave you the correct thing. The C++ I/O streams don't bother to do anything other than simply stop working if you try to perform an invalid conversion. You must explicitly check to make sure it worked before continuing.
You should learn 'error handling'. The program you wrote itself has many repetitions of code. This can be eliminated by using functions. I think you better use the isdigit() function to check whether user entry is a digit or not. Googling it.