I'm making a Text Adventure in C++ as an attempt to learn the language. The player interacts using commands like look or travel north. So far I've got code that converts the text to lowercase and then splits it into a Vector. This works fine for one word commands, but when I go to implement longer commands I find that the length always = 1 and accessing over that returns in an error. Here's my code:
//Input function.
void Input() {
const char delim = ' ';
//Processing
std::cin >> input;
std::transform(input.begin(), input.end(), input.begin(),
[](unsigned char c) { return std::tolower(c); });
std::vector<std::string> out;
split(input, ' ', out);
//Commands
if (out[0] == "exit")
exit(0);
else if (out[0] == "help")
Help();
else if (out[0] == "look")
Look();
else if (out[0] == "travel" || out[0] == "go") {
//This code will never run.
if (int(out.size()) == 2) {
Travel(out[1]);
}
}
}
//Split function
void split(std::string const& str, const char delim, std::vector<std::string>& out)
{
std::stringstream ss(str);
std::string s;
while (std::getline(ss, s, delim)) {
out.push_back(s);
}
}
Any help would be vastly appreciated! Thanks, Logan.
Fun fact, when you do this:
std::cin >> input;
It reads characters up until the next whitespace character, and puts those into the string. That means input
will only contain the first word you entered.
Want to get the whole line? Well, clearly, you already know how to do that, just call std::getline
:
std::getline(std::cin, input);