Switch statement problem

The program works fine with numbers 1-9, but when I put in 10 it will print out a "I" when it should print out the default.

#include <iostream>

using namespace std;

int main()
{
char number;

cout << "Enter a number from 1 to 5: ";
cin >> number;
switch (number)
{
case '1': cout << "The Roman numeral equivalent is: I" << endl;
break;
case '2': cout << "The Roman numeral equivalent is: II" << endl;
break;
case '3': cout << "The Roman numeral equivalent is: III" << endl;
break;
case '4': cout << "The Roman numeral equivalent is: IV" << endl;
break;
case '5': cout << "The Roman numeral equivalent is: V" << endl;
break;
default: cout << "The number must be in the range of 1 through 5 inclusive." << endl;
}

return 0;
}
Last edited on
With 10, it reads one character '1' and does not read the next character '0'.

Why not read an integer and switch on an integer?
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
#include <iostream>

int main()
{
    int number;

    std::cout << "Enter a number from 1 to 5: ";
    std::cin >> number;
    switch(number)
    {
    case 1:
        std::cout << "The Roman numeral equivalent is: I" << std::endl;
        break;
    case 2:
        std::cout << "The Roman numeral equivalent is: II" << std::endl;
        break; 
    case 3:
        std::cout << "The Roman numeral equivalent is: III" << std::endl;
        break;
    case 4:
        std::cout << "The Roman numeral equivalent is: IV" << std::endl;
        break;
    case 5:
        std::cout << "The Roman numeral equivalent is: V" << std::endl;
        break; 
    default:
        std::cout << "The number must be in the range of 1 through 5 inclusive." << std::endl;
    }
}
Last edited on
Okay I see. How is case '1': different from case 1:?
'1' is a character, whereas 1 is an integer.
Topic archived. No new replies allowed.