Question:
Can I use switch function with operators?
Steffie
2013-01-30 11:22:33 UTC
So I'm asking the user to input an operator, and depending on what he inputs, the answer is going to differ accordingly. I wanted to add a switch here, but the compiler is giving me an error.

printf("Enter an operator :");
scanf("%c", &operator);
switch (operator) {
case +:
printf (blah blah)
break;
case *:
printf (blahblah)
break;
}

for some reason this is not executing. i tried adding single quotation marks around the characters but they're not working. or are switch statements only used with integers?
Three answers:
Pyros
2013-01-30 11:28:41 UTC
Place "" around the operators.

Switch (operator)

{

Case "+":

printf("something");

Break;

}



Follow that formula and it should work. Make sure the operators the uses are entering are saved as strings or chars depending on your language of choice and your circumstances.
roger
2013-01-31 16:40:20 UTC
yep you can:

put the character constants in single quotes ' '



char operator;

printf("Enter an operator :");

scanf("%c", &operator);

switch (operator) {

case '+':

printf ("blah blah")

break;

case '*':

printf ("blahblah")

break;

}
jplatt39
2013-01-30 20:05:19 UTC
When in doubt use an int.

1.for +

2. for *

blah for blah.



Edit: You can also do:

enum {'+','-','*','/'}; But then you would have to use single quotes.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...