Use switch with number case and char case

55,689

Solution 1

Just treat the integers as characters like this;

By the way, you probably want to read a new character each time through the while loop, otherwise you'll get stuck printing forever. The default case below allows us to break from the loop.

int main() {
    char i,a = 0;
    printf("Write something:");
    scanf("%c", &i);
    do{
        switch (i)
        {
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
            printf("%c",i);
            break;
        case 'e':
            a=1;
            break;
        default:
            printf("This is not a number"); 
            break;
        }
    }while (a==0);
}

Solution 2

When you say 'e', you are actually saying "The value of 'e'". This is the ASCII value. The decimal value of 'e' is actually 101.

To make this work, you could use the char datatype. Read in the data as a char, and in your switch statement, instead of a digit, use a char instead. e.g.

switch (i)
{
case '1': 
  //do something
  break;
Share:
55,689
Someonewhohaveacat
Author by

Someonewhohaveacat

Updated on May 04, 2021

Comments

  • Someonewhohaveacat
    Someonewhohaveacat almost 3 years

    I want to make a switch loop.

    If input is from 1 to 5. It will print a number. Else it will print "this is not a number". And if the input is 'e'. The switch loop should be ended.

    I can make the number part, but I don't know how can I to make input with 'e'. It just won't read. Here is my code:

    int main() {
    int i,a = 0;
    printf("Write something:");
    scanf("%d", &i);
        do{
        switch (i)
        {
        case 1:
            printf("1");
            break;
        case 2:
            printf("2");
            break;
        case 3:
            printf("3");
            break;
        case 4:
            printf("4");
            break;
        case 5:
            printf("5");
            break;
        case 'e':
            a=1;
            break;
        default:
            printf("This is not a number”); 
            break;
        }
    }while (a==0);}
    

    My problem is I can't have input as 'e' or any char. Because if I do that I will create a paradox loop or just don't work at all. Where am I wrong?