Switch statement with char*?

Started by
16 comments, last by ChaosPhoenix 21 years, 7 months ago
Im trying to use a switch statement to determ what action the user wants by commands, however, The user text commands are stored as char* and I apparently can''t use that in a Switch statement. Any suggestions to allow me to use my char* in a switch statement or somehow convert it to just char?
Advertisement
switch statements only work with integral types. You''ll have to use if/else statements.

If I had my way, I''d have all of you shot!

codeka.com - Just click it.
you can use a command list array and search the command in the array ,then you get a integer you can use it in your switch statement.

/*- John Dragon-*/
/*- John Dragon-*/
I tried if/else but it seems to run both IF statements instead of just one or the other.

if(TempArray == "Computer1")
{
Computer1.Time += time;
return;
}
if(TempArray == "Computer2")
{
Computer2.Time += time;
return;
}

If the Array reads Computer1 Its suppose to just add that time variable to the Computer1 class and that works fine,but If I try Computer2 it doesnt add anything and exits.

Any Suggestions?

[edited by - ChaosPhoenix on September 3, 2002 5:38:56 AM]
You can''t use == to compare c-style strings. Use strcmp, or use the c++ string class.
Never do string comparison this way! Instead, use strcmp().
using elseif might be a little nicer too.. and probably much faster if you want to execute code behind the if statements
(this way it checks every if.. even if we already found the thing we wanted)

[edited by - The Eternal on September 3, 2002 6:13:20 AM]
They are right, use strcmp, but it is even easier to overload the == operator like this:

bool operator==(const char *c1, const char *c2)
{
return (strcmp(c1, c2) < 0)
}

That way you simplify your code a lot and don''t have to remind yourself of how strcmp works every time.
-----------------------------Final Frontier Trader
Overloading is a possibility, but it does add another layer to the functions calls. so an extra function is called which takes extra time. and remembering how stricmp works isn''t hard at all
quote:Original post by biovenger
They are right, use strcmp, but it is even easier to overload the == operator like this:

bool operator==(const char *c1, const char *c2)

That won''t work. It''s only possible to overload operators where at least one of the operands is a user-defined type.

This topic is closed to new replies.

Advertisement