+ 1
How to use switch case with string in c
18 odpowiedzi
+ 2
For char, similar to the example in this lesson:
https://www.sololearn.com/learn/C/2924/
Example for switch with char
https://code.sololearn.com/c2dbDGmVqdS5/?ref=app
For string, use if-else :
https://stackoverflow.com/questions/4014827/best-way-to-switch-on-a-string-in-c/4014943
+ 3
https://code.sololearn.com/c2dbDGmVqdS5/?ref=app
Aryaman Mishra 🇮🇳 switch isn't limited to int.
+ 2
Can't use switch on a string as it is not an integral data type.
+ 1
See if u are taking arguement inside switch parenthesis, they have to be constant or constant expression. In your code you have declared num to abc and in cases you have written 1, 2, etc. So your code compares num=1, which is not valid as you are comparing char data type with integer data type. That's why it shifts to default case. Hope it helps
+ 1
The case label should reduce to an integer. You can take value of num as an integer and then proceed.
+ 1
I know it works for char but for string too?
+ 1
hmm... no, have to use if-else like this:
https://stackoverflow.com/questions/4014827/best-way-to-switch-on-a-string-in-c/4014943
+ 1
Yes I was saying that only. But in this question sandeep has initialized num to abc which is not a character. Thanks for the code though🙂
+ 1
Yes thanks lot
0
Give some example
0
Check above code am getting wrong output for this
0
Can I get the correct code
0
Anudeep P Hosur Please make Aryaman's answer as best, because his answer is relevant, specific and accurate. Thanks.
0
I hope anudeep has got his answer.
0
syntax:
switch(statement)
{
case condition1: //statement;
break;
case condition2: // statement;
break;
........
default: //statement
}
Here case work same as if, else if while default work as else statement. Important thing is don't forget to add break statement after every case or you won't get desired output as beginner.
0
The overall code is same as integer or any other data type
Just the different is while placing string in condition just wrap it with double quote.
For example
Switch (statement)
Case "condition1": //statement
Break;
Case "condition2"://statement
Break;
And so on
0
Anudeep P Hosur
I think it is better if you use if-else...
Here are 3 reasons why,
1) switch statement on takes constant value
2) string is represented as array of char, so it cant be constant
3) even if you pass string, it will just gives you warnings but main problem will occur at case part which wil either takr int or char. And i think it is nearly impossible to assign each string in case an constant value
Hope this can help you..... 😊