Start learning free

LESSON 14 OF 343 · VARIABLES

Type Conversion in C++: to_string, stoi and Casts

Lesson Read the full explanation

In C++, every value has a type: int, double, string, and so on. Sometimes you need to convert a value from one type to another.

Common type conversion functions:

to_string(x)   // converts int or double → string
stoi(s)        // converts string → int
stod(s)        // converts string → double
(int) x        // casts double → int (drops decimal)

Here are some examples:

int score = 42;
string scoreStr = to_string(score);   // "42"

double weight = 70.8;
int weightInt = (int) weight;         // 70  (decimal dropped)

string count = "100";
int countInt = stoi(count);           // 100

Note that casting a double to int with (int) simply drops the decimal - it does not round.


Assignment
Follow the Coding Tutorial and convert each variable to a different type!


Hint
Use to_string(), (int) casting, and stoi().

STEP 1 OF 3
    Ctrl + Enter to check

    C++ · VARIABLES

    Type Conversion in C++, explained

    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 (an int or a double, among others) into a string.
    • stoi(s) parses a string into an int. Its sibling stod(s) parses into a double.
    • (int) x is a cast that turns a double into an int by 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:

    • stoi stops at the first character that cannot be part of a number and ignores the rest. stoi("12abc") returns 12, and leading spaces are skipped, so stoi(" 7") returns 7.
    • If the string does not start with a number at all, stoi throws std::invalid_argument. If the number does not fit in an int, as in "99999999999", it throws std::out_of_range. Code that handles user input should wrap the call in try and catch.

    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.

    1. Convert age to text. Declare a string named ageStr and give it to_string(age). The new variable holds "25".
    2. Convert price to an integer. Declare an int named priceInt and assign (int) price. Since price is 9.99, the result is 9, not 10.
    3. Convert year to an integer. Declare an int named yearInt and assign stoi(year), which gives 2024.

    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.99 is 9.
    • Adding a number to a string literal. "Age: " + 25 does not build the text "Age: 25"; it is pointer arithmetic on the literal and compiles into something wrong. Write "Age: " + to_string(25).
    • Calling stoi on text that is not a number. It throws instead of returning 0.
    • Forgetting that to_string on a double adds zeros. Compare strings only after you know the exact format.

    Key takeaways

    • to_string converts numbers to strings, stoi and stod convert strings to numbers.
    • A (int) cast truncates toward zero and never rounds.
    • Parsing functions throw exceptions on bad input.
    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free