C++ Converting Strings and Numbers
In this page:
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
#include <iostream>
#include <string>
int main() {
int age = 25;
std::string text = std::to_string(age);
std::cout << text << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
#include <string>
int main() {
std::string input = "42";
int number = std::stoi(input);
std::cout << number + 1 << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
#include <string>
int main() {
std::string input = "3.14";
double value = std::stod(input);
std::cout << value << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- C++ Arrays Introduction
- C++ Looping Through Arrays
- C++ Omitting Array Size
- C++ Array Size
- C++ Multi-dimensional Arrays
- C++ Arrays & Functions
- C++ Strings (C-style)
- C++ std::string
- C++ String Concatenation
- C++ Converting Strings and Numbers
- C++ String Length
- C++ Accessing String Characters
- C++ using namespace std
- C++ String Methods
- C++ Array of Strings