Numbers in Strings
The string "12" isn't a number. It's two characters, '1' and '2', and C++ can't calculate with it:
#include <iostream>
#include <string>
int main() {
std::string level = "12";
int nextLevel = level + 1;
std::cout << nextLevel << std::endl;
return 0;
}The program doesn't compile:
main.cpp:6:27: error: invalid operands to binary expression ('std::string' (aka 'basic_string<char>') and 'int')A string becomes a number with std::stoi() (string to int) or std::stod() (string to double). The way back, std::to_string(), you know from the Functions lesson:
std::string level = "12";
int nextLevel = std::stoi(level) + 1;
std::cout << "Next level: " << nextLevel << std::endl;
double speed = std::stod("1.5");
std::cout << "Speed: " << speed * 2 << std::endl;
std::string text = "Level " + std::to_string(nextLevel);
std::cout << text << std::endl;This prints:
Next level: 13
Speed: 3
Level 13std::stoi() skips spaces at the start, reads the digits and stops at the first character that isn't one, so std::stoi("250 gold") is 250. A minus at the start works too: std::stoi("-5") is -5.
But when the string doesn't start with a number, there's nothing to read, and the program stops:
std::string amount = "lots";
int gold = std::stoi(amount);
std::cout << "Gold: " << gold << std::endl;The output ends with:
std::invalid_argument: stoi: no conversion
RuntimeError: unreachableinvalid_argument means that the function got a value it can't work with, and no conversion that it couldn't turn it into a number. std::stod("fast") ends the same way, only with stod in the message. A player can type anything, so check a string before you convert it, for example with std::isdigit() on its first character.
Instructions
- 1
In the shop, the player types
buyand the number of potions. Take the part ofcommandafter the space, turn it into a number withstd::stoi(), and print what the potions cost:Total: 75 gold. The test also runs your program with other commands and prices. - 2
What if the player types
buy lots? Try it: the program stops with an error. Before you callstd::stoi(), check the first character of the amount withstd::isdigit(). When it isn't a digit, printNot a number: lotsinstead of the total. Then change the command back to"buy 3": the test runs your program with other commands itself.