Very basic question...

Hi I'm new to this forum, and I just need to know one thing.
Is there any other way to write:
1
2
3
4
if (variable == 1 || variable == 2 || variable == 3)
{
     cout << "You win the game!";
}

Just asking because I want my code to be a bit cleaner.
I'm sure there must be. It seems very inefficient this way, and it bugs me.
I feel like I should know this, and that also bugs me.

Thanks in advance for your response that I get within the next 2 seconds!(?)



Well, you could check ranges using < and >. If you have a character or integral type, you could stack cases on a switch as well, I suppose.
Oh well actually in my case I'm using strings... Probably should have mentioned that.
I'll be a bit more specific this time.
1
2
3
4
5
if (direction == "northeast" || direction == "southeast" || 
direction == "southwest" || direction == "northwest")
     {
           cout << "One direction at a time please.\n";
     }

Last edited on
Unfortunately there isn't much you can do about that.

I remember when writing a command parser, I had a map that mapped strings to command functions. Something to the effect of:
1
2
3
4
5
6
7
8
9
10
11
std::map<std::string, funcptr_t> commands;
commands["north"] = &(coms::North);
commands["look"] = &(coms::Look);
//...
commands["quit"] = &(coms::Quit);
commands["exit"] = &(coms::Quit);
//...as your example
commands["northeast"] = &(coms::InvalidDirection);
commands["northwest"] = &(coms::InvalidDirection);
commands["southeast"] = &(coms::InvalidDirection);
commands["southwest"] = &(coms::InvalidDirection);

This meant I could throw the input into a find() call instead of having to do long if checks, and could have synonyms for different commands without adding clutter in an if statement. I'm sure there is a better way of doing it, but that's what I had when I was experimenting with it.
I see, well I guess it really isn't a big deal. The way I'm writing my code there's bound to be clutter, but I'm pretty new to c++ so that's expected.
Thanks! That's all I really needed to know.
@Maddsc16 Read up on the switch statement. Problem is, with C++ you can't use strings in switch statements. However there are ways you can work with this, such as relating your string to an ID number and using that ID in the switch.
Could you possibly use if else (if else...) that might speed it up a bit. But only when the correct variable hits the first if statement...
Topic archived. No new replies allowed.