0

I'm building a text-based game in C++ as a side project in my learning, and so I'm trying to find a way for string to be evaluated in two halves. It will check the first word, then if the word is recognized, it will see what the word after it is. For example if the input in a getln(); is "take apple" it will recognize the "take", then check to see what exactly you are taking in the second half of the string. Right now the only way I can think of doing it is by the player entering "take" and this leading into a ton of nested if/else statements.

2 Answers2

1

You could try to tokenise the input string into its components. Then, given that you use C++, I would suggest a conditional-free design with polymorphy:

Create a basic Type:

class Command {
  public:
    virtual void exec(::std::vector<::std::string> parameters) = 0;
};

Then create subcommands, e.g.:

class TakeCommand : public Command {
  public:
    virtual void exec(::std::vector<::std::string> parameters);
};

Then, during startup, build yourself, a dictionary (or a Trie, if you're feeling dandy) of type

::std::map<::std::string,::std::shared_ptr<Command>> commandProcessor;

As this is a map, you can check if the command exists:

auto const it = commandProcessor.find(tokens[0]);
if (it != commandProcessor.end())
  it->second->exec(tokens);
  // you might want to strip the first token from the vector first!

Any type/function you are unfamiliar with, you can lookup at http://en.cppreference.com/w/

bitmask
  • 25,740
  • 12
  • 80
  • 142
0

What I would do is get the input from the user and then split the string using " " as the delimeter. You'd still have a nested if statement but it would eliminate the need for the user to enter input twice.

See this post to read more about splitting strings in C++.

Community
  • 1
  • 1
ekrah
  • 544
  • 5
  • 16