My program is crashing when I type in the the character that registers for the else condition. The if, and the else if work perfectly fine. Any ideas?
Appreciate the help.
// LEGAL DRINKING AGE
#include <iostream>
using namespace std;
int main()
{
int age;
bool answer;
answer = true;
while (answer == true)
{
cout << "Please enter your age: ";
cin >> age;
Your code looks fine and works well when you enter a number. Of course it crashes when you input any other characters than digits for age or any other key than 0 or 1 for answer.
One way to solve it is to get the input as a string, check that it is valid and convert it to an int or bool.
The idea is; if the input is anything outside the (decision makers) boundaries for the if and else if, which would be anything that is not the integers 1-125, that it would output the else: "Are you human?".
For instance, if I type in 'a' for the input. I get that crash i mentioned, instead of the else statement.
Oh.. It's crashing because mixed data types. Obvious oversight on my part. Thanks Thomas I see what you mean. Is there any reason to convert it though?
One reason might be to make it work. Telling if a string represents a number that is above and below a particular value isn't a particularly convenient thing to do without converting the string into an integer value.
Here's a version using a string and conversion (and execeptions, since std::stoi may throw one.)