Skip to main content
gamedev.net
🔒 Locked

Using switch() on strings

Started by darkchrono4 12 replies 1.8k views
Original Post
darkchrono4
darkchrono4
I don''t think its even possible, but can you do a switch() statement on a string? Whenever I try to do something like that I get "No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called" as the error. I could do what I need to do with the switch using ifs but thought it would be cleaner with a switch instead.
hollowMedia
hollowMedia
If I wish to do a switch on a string I do this


switch( tolower( *pszString ) )
{
case ''a'':
{
if( !strcmp( pszString, "astringstartingwiththelettera" ) )
foo();
else if( !strcmp( pszString, "anotherstringstartingwitha" ) )
bar();
else
errrFunc();
}
break;

case ''b'':
{
...
}
}


Otherwise, unless you''re in Java or VB switch won''t work on strings. Actually, I am not even sure if it works in Java. I thought it did. I don''t know.

[xian]
gimp
gimp
It''s a bit dodgy but could a hash or CRC of the string work here. I''m originally from VB land too and mis this too...

Chris Brodie
http:\\fourth.flipcode.com
Chris Brodie
a person
a person
you cant use strings in switch statments.

TornSpace, your example only compares the first letter in the string. unfortunatly, not very usefull. a good way to compare many strings at once is to do something as follows, this assumes that you are doing this becuase you want to run particular functions:

  

// this is PSUDEO code!


struct Cmds
{
char *string;
(int)(*Function)(char *parms);
};

int doload(char *filename)
{
// magic math stuff goes here

if(parms==NULL)
return CMD_INVALIDPARMS;

if(open(filename)==FAILED)
return CMD_FILENOTFOUND;

return CMD_OK;
}

int dosave(char *filename)
{
if(parms==NULL)
return CMD_INVALIDPARMS;

if(write(filename)==FAILED)
return CMD_SAVEFAILED;

return CMD_OK;
}

Cmds myCmds =
{ "load", doload,
"save", dosave,
NULL, NULL
};
// the last cmd should have a null string

// or you could just keep track of the number of commands


int CheckCommand(char *strToCheck)
{
for(;;)
{
if(myCmds[i].string==NULL)
return CMD_NOTFOUND;
// there are better functions then strstr

if(strstr(myCmds[i].string, strToCheck)==myCmds[i].string)
return myCmd[i].Function(strchr(strToCheck, '' ''));
}
return CMD_NOTFOUND;
}


this system above is designed for a console style interface. you could use similary method for scripting engines. you can add more to the struct to include help messages and such. even modify the functions to be classes or how ever you think it best to abstract away the commands.
D
D
A simple rule to follow when using switch statements (even in java) is that they only work on elementary types, such as char, int, short, long, (float, and double I''m not so sure of - don''t think so really, maybe if you can convert them to an int they would work).

Even though the String type is considered "elementary" in java it is actually a class, like Integer etc, so it will not work in switch statements..

I''m pretty sure that this holds for most languages - C, C++, Java, VB, QB etc.

Dæmin
(Dominik Grabiec)
dominik.grabiec@student.adelaide.edu.au
Daemin(Dominik Grabiec)
darkchrono4
darkchrono4
a person, maybe because I don't completely understand all of this but I can't get it to compile. I put all of this above main and commented out the function code and gave values for all the returns except for the one. When I do try and compile the first errors I get are "type 'int' unexpected" and "unexpected token(s) preceding ';'" on the struct. I get a whole bunch more but they all seemed to be related to the struct error. The other problem is I'm using a string and a vector string in main and I get a bunch of errors about them as well. If it is supposed to be psudeo code I don't see anything wrong except you are referring to functions that don't exist and and some constants that haven't been defined.

Edited by - darkchrono4 on December 21, 2001 3:42:00 PM
Cyberdrek
Cyberdrek
quote:
Original post by darkchrono4
a person, maybe because I don't completely understand all of this but I can't get it to compile. I put all of this above main and commented out the function code and gave values for all the returns except for the one. When I do try and compile the first errors I get are "type 'int' unexpected" and "unexpected token(s) preceding ';'" on the struct. I get a whole bunch more but they all seemed to be related to the struct error. The other problem is I'm using a string and a vector string in main and I get a bunch of errors about them as well. If it is supposed to be psudeo code I don't see anything wrong except you are referring to functions that don't exist and and some constants that haven't been defined.

Edited by - darkchrono4 on December 21, 2001 3:42:00 PM


if you read the first comment of his code, it says that it's pseudo-code. In other words, you have to write the correct code. It's sort of like a guide... Analysts write pseudo-code to tell the programmers how the program should handle and then give that to programmers so they can write the code for it...



"And that's the bottom line cause I said so!"

** I WANT TO BE THE MODERATOR FOR THE LINUX FORUM **

Cyberdrek

Resist Windows XP's Invasive Production Activation Technology!

"gitty up" -- Kramer
/(bb|[^b]{2})/ that is the Question -- ThinkGeek.com
Hash Bang Slash bin Slash Bash -- #!/bin/bash

Edited by - cyberdrek on December 21, 2001 4:02:06 PM
[Cyberdrek | ]
a person
a person
right on cyberderek, its more educational using psudeo code since it makes you understand since you have to code it as well as being portable to most lnagugaes since its theory and not real code. funnily enough, the psudeo code is pretty close to actual c/c++ code. the constants are left for you to define, since its up to you to define what errors you expect to happen and how to handle them. the functions open() and write() are real functions, but i am not going to use real parms for them, since that part is not important to the question you asked. you probally should read up on function pointers, it will help you.

FYI:
[qoute]
pseudo
adj : (often used in combination) not genuine but having the appearance of; "a pseudo esthete"; "pseudoclassic"

TerranFury
TerranFury
Just use if...else with strcmp(...)
Dak Lozar
Dak Lozar
I like the solution that hollowMedia provided - it gives you a way to limit the number of string compares you would have to perform on a given search.

I have implemented a similar strategy when using strings in C++. Basically I determine the length of the string and switch on the length. The flaw to this approach is obvious... as more strings are needed to be checked you have to maintain/modify the switch statement...

I am typing this from memory so there may be errors -
  
void SomeStringCompareFunc(char* pString)
{
// assumes the string has been de-sensitized :)

int Len = strlen(pString)
switch( Len )
{
case 3:
{
if( !strcmp( pString, "cat" ) )
cat();
else if( !strcmp( pString, "dog" ) )
dog();
else errrFunc();
}
break;
case 4:
{
if( !strcmp( pString, "dood" ) )
dood();
else if( !strcmp( pString, "girl" ) )
girl();
else errrFunc();
}
break;
case 5:
{
...
}
}
}

I would suggest finding another way... one that comes to mind is a binary tree. Compiler writers have to deal with this sort of stuff all the time and they utilize binary trees to solve this.

Dave "Dak Lozar" Loeser
Dave Dak Lozar Loeser
"Software Engineering is a race between the programmers, trying to make bigger and better fool-proof software, and the universe trying to make bigger fools. So far the Universe in winning."--anonymous
darkchrono4
darkchrono4
Alright I guess that I''m a complete moron on this. I haven''t messed with function pointers since I went through them in my book. I changed the arugement on the function from the char to an int pointer. And turned myCmds to an array of three elements. But when I try to initialize them I get ''cannot convert from ''const int'' to ''int (__cdecl *)(int *)'' and ''cannot convert from ''char [5]'' to ''int (__cdecl *)(int *)'' as the errors. And if I use the braces to seperate the initializations the way I''m supposed to I get several more errors dealing with the braces. Any ideas on this at all? I''m about ready to give this whole thing up.
a person
a person
post your code dealing with how you set up the structure and fill it, makes it easier to see where the problem is.

as to TornSpace the original post as i see it:
quote:

I don''t think its even possible, but can you do a switch() statement on a string? Whenever I try to do something like that I get "No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called" as the error. I could do what I need to do with the switch using ifs but thought it would be cleaner with a switch instead.



unfortunatly i see no mention of switching on a string to compare only the first letter. maybe you are misreading the post or i am illiterate.
darkchrono4
darkchrono4
This is what I got:

struct Cmds
{
char *string;
int (*Function)(int *x);
};

And to fill it out:

Cmds myCmds[3] =
{
{
"load", 1
}

{
"save", 2
}

{
NULL, NULL
}

};

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.