← Back to C++ Course | Chapter 6: Arrays & Strings | Lesson 10 of 15

C++ Converting Strings and Numbers

std::to_string converts a number into a string, and functions like stoi and stod convert a string back into a number, the two directions needed to move data between text and numeric form.

Converting a Number to a String

std::to_string converts any of C++'s built-in numeric types into a std::string, producing its standard text representation, ready to be concatenated or displayed.

Example: Converting a Number to a String

cpp
#include <iostream>
#include <string>

int main() {
	int age = 25;
	std::string text = std::to_string(age);
	std::cout << text << std::endl;
	return 0;
}

Converting a String to an int

stoi (string to int) parses the leading numeric portion of a string and returns it as an int, throwing an exception if the string doesn't start with a valid number.

Example: Converting a String to an int

cpp
#include <iostream>
#include <string>

int main() {
	std::string input = "42";
	int number = std::stoi(input);
	std::cout << number + 1 << std::endl;
	return 0;
}

Converting a String to a double

stod (string to double) works like stoi but parses a floating-point number, returning a double, useful for reading decimal values that were originally entered or stored as text.

Example: Converting a String to a double

cpp
#include <iostream>
#include <string>

int main() {
	std::string input = "3.14";
	double value = std::stod(input);
	std::cout << value << std::endl;
	return 0;
}

Handling Invalid Conversions

Both stoi and stod throw a std::invalid_argument exception if the string doesn't begin with a valid number at all, so conversions from untrusted input should be wrapped in a try-catch block.

Example: Handling Invalid Conversions

cpp
#include <iostream>
#include <string>

int main() {
	std::string bad = "abc";
	try {
		int number = std::stoi(bad);
		std::cout << number << std::endl;
	} catch (std::invalid_argument &e) {
		std::cout << "Invalid number" << std::endl;
	}
	return 0;
}

Formatting Numbers as Strings

Combining to_string with string concatenation is a common way to build a formatted message that mixes fixed text with computed numeric values.

Example: Formatting Numbers as Strings

cpp
#include <iostream>
#include <string>

int main() {
	int score = 95;
	std::string message = "Your score: " + std::to_string(score);
	std::cout << message << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.