Have you ever converted int to 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 in C++?
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++?
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.
How to Convert Int to String in C++ with Example
There are several ways in C++ by which you can convert int to string. Below are a few points on how to convert int to string in C++ with examples using 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 C++ string conversion 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 int to string in C++, the two commonly used methods 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 the difference between to_string and stringstream C++ in terms of 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.
Here is an example that shows the difference between to_string and stringstream in C++.
Example:
Output:
This C++ Program shows the difference between to_string and stringstream C++ by comparing 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.
Why Convert Numbers to Strings in C++?
Converting numbers to strings in C++ is useful due to the following important reasons:
- Displaying Output: Converting int to string in C++ is important to show numerical values as part of messages in a user interface, console output, or logs.
- Logging and Debugging: Numbers are converted to strings to include them in log files and debug messages.
- File or Network Output: Numbers are converted to strings when there is a need to write data to text files or send it over a network in a text-based format.
- Concatenating with Other Strings: Converting numbers to strings in C++ is important to combine numbers with text for creating filenames, status messages, or labels.
- Interfacing with Libraries or APIs: Some functions or libraries require inputs as strings, even when you’re passing numbers; thus, numbers are converted to strings.
- User Input/Output Matching: When there is a need to read and display numeric values entered by users, C++ string conversion is necessary for validation or formatting.
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.
Method |
Performance |
Ease of Use |
Flexibility |
Best Use Case |
std::to_string() |
Fast |
Very easy |
Low |
Simple numeric to string conversions |
std::stringstream |
Slower than to_string |
Easy but verbose |
High |
Converting multiple types or formatting complex outputs |
sprintf() (C-style) |
Very fast |
Moderate (C-style) |
Very high (custom formats) |
High-performance needs or legacy C compatibility |
boost::lexical_cast |
Slower |
Easy |
Medium |
Type conversions when Boost is already in use |
Conclusion
In many real-world applications, such as logging, UI messages, file writing, etc., it is a common activity to convert an int to string 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 int to string in C++ without using to_string()?
Yes, you can use stringstream, sprintf(), or boost::lexical_cast to convert int into string in C++.
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.
Q9. How to use sprintf in C++ to convert int to string?
To convert an int to a C-style string using sprintf in C++, declare a char array of sufficient size and then use sprintf(charArray, “%d”, yourIntVariable);
Q10. How to convert int to string with leading zeros in C++?
To convert an integer to a string with leading zeros in C++, you can use this syntax std::string str = (std::ostringstream() << std::setw(5) << std::setfill('0') << num).str();