Reputation: 144
I have this code who try to compare strings in Switch Case:
char input[50+1];
fgets( input, 50, stdin );
switch (input) {
case "register": NSLog(@"Voce escolheu a opcao de cadastro");
break;
case "enter": NSLog(@"Voce escolheu a opcao de entrada");
break;
case "exit": NSLog(@"Voce escolheu a opcao de saida");
break;
}
This command returns me an error, because I believe that we can not write a text after the 'case' command. I would have someone could help me solve this problem, I believe there are other ways to make a Switch Case using strings, but how?
Upvotes: 0
Views: 99
Reputation: 9532
The lookup option works pretty well. Consider:
NSArray *strings = @{@"string1", @"string2"};
NSUInteger index = [strings indexOfObject:input];
switch(index) {
case 0:
//stuff for string 1;
case 1:
// stuff for string 2:
case NSNotFound:
// not found;
}
Upvotes: 1
Reputation: 237110
You can't. Switch only works with integers. The best options are a chain of if-else statements or a lookup table (e.g. an NSDictionary).
Upvotes: 0