Splitting a Command
Together, find() and substr() split a string into parts: first find where the parts meet, then take the part before that place and the part after it. In a full name, the parts meet at the space:
std::string name = "Aria Stormwind";
int space = name.find(' ');
std::string firstName = name.substr(0, space);
std::string lastName = name.substr(space + 1);
std::cout << firstName << std::endl;
std::cout << lastName << std::endl;This prints:
Aria
StormwindThe space is at index 4. The first name is the part from index 0 with the length 4, which is everything before the space. The last name starts one character after the space and goes to the end. Mind the + 1: without it, the last name would start with the space.
Old text adventure games were played exactly like this. The player types a command such as take sword or go north, and the game splits it at the first space into a verb, what to do, and an object, what to do it with. Everything after the first space belongs to the object, so in drink red potion, the verb is drink and the object red potion.
What if there is no space? Run the same code with the name "Aria", and it prints:
Aria
AriaThere's no error, but the result is wrong. find() found no space, so space holds -1. The last name then starts at index -1 + 1, which is 0, and substr() takes -1 as the biggest possible length, which means up to the end. So when a string may have no space, check the result of find() before you split it.
Instructions
- 1
Split
commandat the space into the verb and the object, and print them on two lines:Verb: takeandObject: lantern. The test also runs your program with other commands. - 2
Some commands are a single word, such as
look. Then the whole command is the verb, and there is no object. Change the program so that for a command without a space, it prints onlyVerb: look, without the line with the object. The test runs your program with"look"too. (To try it yourself, change the command, run the program, and then change it back to"take lantern".)