Using an operator on a switch case

Asked

Viewed 492 times

3

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 that by introducing a special character, for example, +, -, / (etc), I show myself in the case, "Hello World" instead of having to put 1. Is there a way? Something like:

#include <stdio.h>

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

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

}
  • My C is rusty, but try looking for the symbols by matching char, for example, case #10

  • Did any of the answers solve the problem? Do you think you can accept one of them? See [tour] how to do this. You’d be helping the community by identifying the best solution. You can only accept one of them, but you can vote for anything on the entire site.

3 answers

1

I don’t know if I understood your doubt correctly, but if I understand it correctly it is possible yes

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;
}

It is actually possible to recognize by char type any character that is in the table ASCII. Take a look, it might just be that.

Note that I had to use a variable of type char and not int to make it work. In this case your program will compare to any type of character, in case what you search is the character corresponding to the sign "+".

Note also that in this case I used single quotes, this is because in C and C++ it is understood that double quotes are used for strings, which are nothing more than a string (or vector) of characters, the single quotes is understood for even characters.

I hope I’ve helped. :)

1

You can do it:

#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.

1

This is simply not possible. You cannot put what you want into case. There fits only primitive constant values. It is not even possible to use a array, including strings.

What you can use is:

#include <stdio.h>

int main() {
    char op1;
    scanf("%c", &op1);
    switch (op1) {
         case '+':
             printf("ola");
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I took the opportunity to organize the code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.