user3372120
user3372120

Reputation: 144

How to compare strings instead of integers in switch case?

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

Answers (2)

RobP
RobP

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

Chuck
Chuck

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

Related Questions