Start learning free

LESSON 14 OF 667 · VARIABLES

Type Conversion in C++

Lesson

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