Have you ever converted an int to a string in C++ and it didn’t work as planned? With choices such as to_string(), stringstream, sprintf(), and boost::lexical_cast, which approach is the best for speed, safety, or formatting? In this C++ guide to converting numbers to strings, you can learn about the actual differences, performance tips, and best practices.
Table of Contents:
What is an int?
This int (short for integer) is a base data type in C++ that holds whole numbers. It is usually 4 bytes in size and can have positive and negative numbers. Integers are used to count, index, do arithmetic, etc. int x = 10; int age = 25.
Example:
Output:
In the above code, the age is assigned as int, i.e, int holds the whole numbers except the decimals. Using the cout, the assigned number is printed on your console.
What is a String?
In C++, a string is a sequence of characters used to hold text. The C++ standard library has a class for strings called std::string, which is designed to work with strings. It supports concatenation, comparison, searching, and other operations. Strings can be initialized directly using the text within double quotes.
Example:
Output:
In the above code, the greeting is assigned as a string, i.e, a string holds the sequence of characters. Using the cout, the assigned number is printed on your console.
Data Type |
Description |
Example |
int |
Integer numbers |
int a = 10; |
float |
Single-precision decimal numbers |
float b = 5.5; |
double |
Double-precision decimal numbers |
double c = 9.99; |
char |
Single character |
char d = ‘A’; |
bool |
Boolean value (true/false) |
bool e = true; |
void |
No value (used for functions) |
void func(); |
How to Declare and Initialize Strings
When combining numbers with text, we have to convert integers to strings. For example, generate user messages such as “Score: 100”, filenames, or logging values. It’s also good for serializing data or writing numbers out as text in files. The conversion is integral in GUI apps, game devs, and formatted output tasks.
Convert Int to String in C++
There are several ways in C++ you can convert integers to strings. Common ways to do so include to_string(), stringstream, sprintf(), and boost::lexical_cast. These are helpful for output formatting, string concatenation, file I/O, and debugging. The syntax (and performance and use case) is slightly different for each method.
1. Using to_string()
to_string() is a standard C++11 function that converts numeric values to strings. It is easy, quick, and needs no extra headers besides. The types that it supports are int, float, double, and long. It is perfect for fast and clean integer-to-string conversion.
Example:
Output:
In this example, to_string(num) translates the number 123 into the string “123”. The output is saved in the str, which is a std::string. Prints the converted string using cout.
2. Using stringstream
stringstream allows you to use strings like streams. It can be used for conversions in both input and output scenarios. It’s slower than to_string(), but operates in pre-C++11 code. Useful for formatting many values into a single string.
Example:
Output:
The std::stringstream ss (infoStr) acts as a buffer. ss << num sends 456 into the stream, ss extracts the string, ”456″. Supports complex formats and multiple values.
3. Using sprintf()
sprintf() is a C-style function that formats strings. It formats numbers and writes the output to a character array. While it’s not as type-safe as C++ methods, it is very flexible. Great for formatting when you require precision or padding control.
Example:
Output:
sprintf() outputs a formatted string to a buffer. %d stands for integer as a format specifier. First, we create a buffer variable, which contains “789”, and assign it to a string. Provide just-in-time formatting, but you will have to be careful of the size of your buffer.
4. Using boost::lexical_cast
boost::lexical_cast is a type-safe (due to using templates extensively) and acts similarly to C++ streams. It contains #include and links to Boost.
Example:
Output:
lexical_cast(num) will produce “1011” from 1011. If the conversion fails, an exception is thrown. Need to install and link properly. Used in a robust application with a clean and secure method.
To convert numbers to strings in C++, the two favourite ones are to_string()and stringstream. While both are great, they differ in terms of speed, readability, and features. To use either one depends on your needs; this comparison explores. Let’s see how they stack up for syntax, speed, and flexibility.
1. to_string() was introduced in C++11 and is optimized for performance and ease-of-use. It’s a one-liner, making code cleaner and quicker to write. It handles basic numeric types like int, float, double, and long. However, it doesn’t allow formatting (e.g., precision, padding).
2. Stringstream from <sstream> allows fine control over formatting. You can combine multiple variables, set precision, use hex/octal, etc. But it’s slower due to stream handling and internal buffering. It’s ideal for complex output, not raw performance.
Example:
Output:
This C++ Program compares the performance of to_string() and stringstream for the conversion of an int to a string a million times. It makes use of the chrono library to time the execution of both approaches in milliseconds. The outcome shows which method is quickest at converting integers to strings multiple times.
Handling Invalid Conversions Gracefully in C++
String-to-integer (or number type) conversion in C++ always comes with the possibility of the string not containing proper numeric data. But your program may crash or be unpredictable if you don’t deal with those cases. You should use functions able to gracefully handle the error of an invalid conversion, such as the right config documentation, which includes exception handling & input inspection functions.
Use stoi() with try-catch
The stoi() function is used to convert a string to an integer. It will throw exceptions as std::invalid_argument or std::out_of_range if the string is not a valid numeric value. To safely catch this type of error, you should use stoi() in conjunction with a try-catch construct. This guarantees that the program does not break, and you can handle wrong input politely.
Example:
Output:
In this example, stoi() attempts to convert “abc123” to an integer. It’s invalid, so it raises an invalid_argument exception. We catch the error and print a user-friendly message instead of crashing.
Best Practices
- Never trust user input without validating it before converting.
- Always use stoi() or boost::lexical_cast to handle conversions safely.
- Don’t use atoi()/atof() unless you’re in legacy C/C++ code.
- Create a helper function, if reusable.
Conclusion
In many real-world applications, such as logging, UI messages, file writing, etc., it is a common activity to convert numbers to strings in C++. There are several ways to do it in C++, like with to_string(), stringstream, or sprintf(), boost::lexical_cast, etc, where each of them has its benefits. Use to_string() for speed and simplicity, but stringstream is more flexible for formatting. The best method depends on your performance requirements, formatting control needs, and the code standards you are following.
Converting Number to String in C++ – FAQs
Q1. Can I convert an int to a string without using to_string()?
Yes, you can use stringstream, sprintf(), or boost::lexical_cast.
Q2. Why is to_string() not working in my code?
You probably use a pre-C++11 version of the compiler; hence, to_string() is unavailable.
Q3. Which is faster: to_string() or stringstream?
For simple conversions to string, to_string() is not only efficient but also faster.
Q4. How can I format a number with leading zeros as a string?
stringstream with setw() and setfill() from .
Q5. What happens if I try to convert a very large int using to_string()?
It will work as long as the int is within range; otherwise, use long long.