String in switch statement

So I have a problem, i wanna use string in switch statement, but when i do that, c++ show me some error like: "switch quantity is not an integer". So question, can im somehow use string in this statement? or i'm must convert it firstly to integer? here's my code example.

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
29
30
31
32
33
34
35
36
 int main()
{
    cout << "Write month name.";
    string monthName;
    int hours;
    cin >> monthName;
    cout << "How many hours in this month you use internet? ";
    cin >> hours;

    switch (monthName) //switch quantity not an integer.
    {
    case "January":
        if (hours <= 744)
        {
            cout << "Hours inputed correctly.";
        }
        else
        {
            cout << "Bad input!.";
        }
        break;
    case "February":
        if (valandos <= 672)
        {
            cout << "Hours inputed correctly.";
        }
        else
        {
            cout << "Bad input!.";
        }
    default:
        cout << "Error, this month did not exist.";
    }
    return 0;
}
You can't use strings with switch statements. Use if instead.
1
2
3
4
5
6
7
8
9
10
11
12
if (monthName == "January")
{
	...
}
else if (monthName == "February")
{
	...
}
else
{
	...
}
Or I guess you could use a lookup table where the user types the month name and the program searches for it and returns the corresponding index.
Simply change the compiler.:)

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;

class ComputeInternetHours
{
    static void Main()
    {
        Console.Write( "Write month name: " );

        string monthName = Console.ReadLine();
        
        Console.Write( "How many hours in this month you use internet? " );
        int hours = int.Parse( Console.ReadLine() );
        

        switch (monthName) //switch quantity not an integer.
        {
            case "January":
                if ( hours <= 744 )
                {
                    Console.WriteLine(  "Hours inputed correctly." );
                }
                else
                {
                    Console.WriteLine( "Bad input!." );
                }
                break;

            case "February":
                if ( hours <= 672 )
                {
                    Console.WriteLine( "Hours inputed correctly." );
                }
                else
                {
                    Console.WriteLine( "Bad input!." );
                }
                break;
    
            default:
                Console.WriteLine( "Error, this month did not exist." );
                break;
        }
    }
}
If you do as vlad said you will be using C# and no longer C++.
Topic archived. No new replies allowed.