Use an operator on a switch case

1

If I do, good wheel:

#include <stdio.h>

int op1;
int main(){
scanf("%d", &op1);

 switch(op1) {
    case 1:
        puts("Hello World");
}

}

I wanted to make when entering a special character, for example, +, -, / (etc), shows me in the case, "Hello World" instead of having to put 1. Has it like? Something like this:

#include <stdio.h>

int op1;
int main(){
 scanf("%d", &op1);

switch(op1) {
 case +:
    puts("ola");
}

}
    
asked by anonymous 22.01.2016 / 11:30

3 answers

1

This is simply not possible. You can not put what you like in case . Only primitive constant values fit. You can not even use an array , including strings .

What you can use is:

#include <stdio.h>

int main() {
    char op1;
    scanf("%c", &op1);

    switch (op1) {
         case '+':
             printf("ola");
    }
    return 0;
}

See running on ideone .

I took the time to organize the code.

    
22.01.2016 / 11:38
0

I do not know if I understood your question correctly, but if I understood correctly, it is possible.

See the code:

#include <stdio.h>

int main()
{
    char op;
    scanf(" %c", &op);

    switch (op) {
         case '+':{printf("Hello World"); break; }
         /* outras opções */
    }
    return 0;
}

In fact it is possible to recognize by char type any character that is in the table ASCII < a>. Take a look, it might just be that. Hope this helps. :)

    
26.01.2016 / 06:19
0

You can do this:

#include <stdio.h>

char op1;
int main() {
    scanf("%c", &op1);

    switch(op1) {
        case '+': puts("ola");
    }

}

Double quotes mean String, single quotes mean Character, so just put single quotes and use a char variable.

    
22.01.2016 / 11:38