Menu
Coddy logo textTech

Type Casting Part 2

Part of the Fundamentals section of Coddy's C++ journey — lesson 15 of 74.

In C++, we can convert numbers to strings and vice versa. To convert a value to string, we can use the std::to_string() function:

int number = 789;
bool isValid = true;
string text1 = to_string(number);  // becomes "789"
string text2 = isValid ? "true" : "false";  // becomes "true"

When you convert a double to a string using to_string(), it will by default show 6 decimal places, even if the original number doesn't have that many decimal places.

For example:

double n1 = 789.0;
string text1 = to_string(n1);
// becomes "789.000000"

double n2 = 789.5;
string text2 = to_string(n2);
// becomes "789.500000"

double n3 = 789.123;
string text3 = to_string(n3);
// becomes "789.123000"

To convert a string to a different type, we have several options:

String to Integer:

string numberText = "123";
int number = stoi(numberText);  // becomes 123

String to Double:

string decimalText = "45.67";
double decimal = stod(decimalText);  // becomes 45.67

Note: When converting strings to numbers, these functions read as many valid characters as possible from the start of the string. They only throw an error if the string begins with an invalid character:

string validStart = "42abc";
int number = stoi(validStart);  // becomes 42 (trailing letters ignored)

string invalidStart = "abc";
int number2 = stoi(invalidStart);  // This will throw an error

Cheat sheet

Convert numbers to strings using std::to_string():

int number = 789;
string text = to_string(number);  // becomes "789"

Converting doubles shows 6 decimal places by default:

double n = 789.5;
string text = to_string(n);  // becomes "789.500000"

Convert strings to integers using stoi():

string numberText = "123";
int number = stoi(numberText);  // becomes 123

Convert strings to doubles using stod():

string decimalText = "45.67";
double decimal = stod(decimalText);  // becomes 45.67

Note: Converting invalid strings to numbers will throw an error.

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals