0

I have a problem while trying to compile my C++ code. As I am still learning C++, I still do not understand most of the advanced commands yet. I was trying to create a program which asks the user's first name, last name, age and gender and displaying it back to the user. This is my source code:

#include <iostream>

int main ()
{
    char firstName[20];
    char lastName[20];
    char age[6];
    char gender[3];

    int i = 0;

    std::cout << "Please enter your full name: ";
    std::cin.getline (firstName, 19, ' ');
    std::cin.getline (lastName, 19);

    std::cout << "Enter your age: ";
    std::cin.getline (age, 5);

    while (i != 1)
    {
        std::cout << "Enter your gender (m/f)";
        std::cin.getline (gender, 2);

        switch (gender)
        {
            case 'm':
                std::cout << "\nHello Mr. ";
                i++;
                break;

            case 'f':
                std::cout << "\nHello Mrs. ";
                i++;
                break;

            default:
                std::cout << "\nThat is not even a gender!\n";
                break;
        }
    }

    std::cout << lastName << "!\n";
    std::cout << "You are " << age << " years old.";

    return 0;
}

When I tried to compile this, my compiler gives me the following error:

NameAgeQ.cpp: In function 'int main()':
NameAgeQ.cpp:24:15: error: switch quantity not an integer

I've tried to code another programs with the 'switch' statements before and it can handle characters. However, in the previous programs I would declare 'gender' as 'char gender;' instead of 'char gender [];'.

Why in this particular case the 'switch' statement doesn't work? Does it not support the array string?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Xarlexus
  • 21
  • 1
  • 1
  • 3

4 Answers4

5

No, it doesn't. A single char is an integer; an array isn't. In your case, this line should fix it:

switch (gender[0])

This means you're using the first char in the array, which is now an integer type again.

David M
  • 71,481
  • 13
  • 158
  • 186
1

You defined gender as a three-character long array, but it seems like you should define it as

char gender;

and use it to store either 'm' or 'f'. This way you can use the switch as you already are.

dorsh
  • 23,750
  • 2
  • 27
  • 29
0

Try replacing gender with *gender in the switch. What happens now is that you use an array as a parameter, though you only want to use the first letter.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
0

The reason is that gender as the name of the array is the pointer to the first element of an array to fix it you should either do switch((*gender)) or as it was said before switch(gender[0])

user989583
  • 43
  • 3