What type conversion is
Every variable in C++ has a fixed type, and the compiler checks every operation against it. A number and the text of that number are different things: 25 is an int you can add to, while "25" is a string you can glue to other text. When a program needs the other form, it converts the value explicitly.
This lesson covers three conversions you will use constantly:
to_string(x)turns a number (anintor adouble, among others) into astring.stoi(s)parses astringinto anint. Its siblingstod(s)parses into adouble.(int) xis a cast that turns adoubleinto anintby dropping the fractional part.
The first two are functions from the standard library, available through <string>. The cast is part of the language itself.
Number to string with to_string
Use to_string when you want to build a message or join a number onto text, because + on strings only accepts other strings:
int score = 42;
string scoreStr = to_string(score);
string message = "Score: " + scoreStr; // "Score: 42"
With a double you get a surprise: to_string always prints six digits after the decimal point. to_string(9.99) gives "9.990000" and to_string(2.5) gives "2.500000". If you need control over the format, use a stream with setprecision instead.
String to number with stoi and stod
Going the other way, stoi reads an integer from the start of the string:
string count = "100";
int countInt = stoi(count); // 100
double ratio = stod("3.5"); // 3.5
Two behaviours are worth knowing before they bite you:
stoistops at the first character that cannot be part of a number and ignores the rest.stoi("12abc")returns12, and leading spaces are skipped, sostoi(" 7")returns7.- If the string does not start with a number at all,
stoithrowsstd::invalid_argument. If the number does not fit in anint, as in"99999999999", it throwsstd::out_of_range. Code that handles user input should wrap the call intryandcatch.
Double to int with a cast
A cast written (int) price tells the compiler to treat the value as an int. For a double this means the fractional part is cut off, in a direction that always moves toward zero:
double weight = 70.8;
int weightInt = (int) weight; // 70, not 71
int negative = (int) -9.99; // -9, not -10
The cast does not round. If you want the nearest integer, add 0.5 to a positive value before casting, or use round() from <cmath>. C++ programmers also write the same cast as static_cast<int>(weight), which is easier to spot when you search a large file. Casting a double that is too large for an int is undefined behaviour, so check the range if the value comes from outside.
You can also assign a double to an int variable without any cast, and the decimal part is dropped silently. The explicit cast makes that intent visible to the next reader.
The exercise, step by step
The editor starts with three variables: age (an int), price (a double) and year (a string). The task is to add a converted version of each one below them.
- Convert
ageto text. Declare astringnamedageStrand give itto_string(age). The new variable holds"25". - Convert
priceto an integer. Declare anintnamedpriceIntand assign(int) price. Sincepriceis9.99, the result is9, not10. - Convert
yearto an integer. Declare anintnamedyearIntand assignstoi(year), which gives2024.
The complete code is:
int age = 25;
double price = 9.99;
string year = "2024";
string ageStr = to_string(age);
int priceInt = (int) price;
int yearInt = stoi(year);
Each new variable has a different type from its source, and each conversion uses the tool made for that pair of types. Original variables are not changed: conversions produce new values.
Common mistakes
- Expecting rounding.
(int) 9.99is9. - Adding a number to a string literal.
"Age: " + 25does not build the text"Age: 25"; it is pointer arithmetic on the literal and compiles into something wrong. Write"Age: " + to_string(25). - Calling
stoion text that is not a number. It throws instead of returning 0. - Forgetting that
to_stringon adoubleadds zeros. Compare strings only after you know the exact format.
Key takeaways
to_stringconverts numbers to strings,stoiandstodconvert strings to numbers.- A
(int)cast truncates toward zero and never rounds. - Parsing functions throw exceptions on bad input.