0

I have a program I made that will check your age and gender. I am using visual studio 2022 to see what happens when debugging.

If I put random letters for the age it skips the cin > gender part which is so weird and the locals shows that age is set to 0 but gender is -52'' . What can I do so it still atleast takes your gender, even if you put weird stuff in for age?

#include <iostream>
using namespace std;
int main()
{
    // prompt user for age AND gender
    //age is int, gender is character
    int age;
    char gender;
    cout << "What is your age? \n" << endl;
    cin >> age;
    cout << "What is your gender? \n" << endl;
    cin >> gender;

    if (gender == 'f' || gender == 'F')
    {
        bool result = (age > 60);
        switch (result)
        {
        case 0:
            cout << "You do not qualify for discount need to be over 60";
            break;
        case 1:
            cout << "You qualify for discount";
            break;
        }
    }
    else if (gender == 'm' || gender == 'M')
    {
        cout << "You do not qualify you need to be female and over 60 \n" << endl;
    }
    else {
        cout << "Wrong gender either use male or female Exiting... \n" << endl;
        return -1;
        exit;
    }

    return 0;
}

This is a picture of the visual studio locals area

enter image description here

Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31
Nerf D
  • 143
  • 1
  • 8

2 Answers2

1

What is needed in this case is some error handling.

Something that can be done is read text input and then try to convert that to a number:

try 
{
    std::string str;
    std::getline(std::cin, str)
    age = std::stoi(str)
}
catch(...)
{
    // ...
}

Then you can handle the errors by catching the exceptions.

https://en.cppreference.com/w/cpp/string/basic_string/stol

Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31
0

When you type bad data for the age and the conversion fails, cin enters an error state. When it's in an error state, it refuses to read anything. The simplest fix would be to just clear the stream after the first

cout << "What is your age? \n" << endl;
cin >> age;
cin.clear();  // But now, the bad integer will become the gender
cout << "What is your gender? \n" << endl;
cin >> gender;

Far better would be to check cin after the first read, and do some error handling, perhaps printing a message and setting the age to some known value.

cin >> age;
if(!cin.good()) {
    // Handle bad input here
}

Note: after the integer read fails, the non-integer data is still in the input stream. If you just clear, that will be the next thing read.

T W Bennet
  • 383
  • 1
  • 7