Table of contents
1.
Introduction
2.
Using to_string()
2.1.
Example
2.2.
C++
3.
Using stringstream
3.1.
Example
3.2.
C++
4.
Using sprintf() function
4.1.
Example 
4.2.
C++
5.
Using boost lexical_cast
5.1.
Example 
5.2.
C++
6.
Frequently Asked Questions
6.1.
What is the main advantage of using to_string() over other methods?
6.2.
Can stringstream handle types other than integers?
6.3.
Is sprintf() safe to use for type conversion in modern C++?
7.
Conclusion 
Last Updated: Jun 12, 2024
Easy

Int to String in C++

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Converting an integer to a string is a common but important concept in C++ programming. It allows you to transform numeric values into their string representations, which is useful for various purposes such as displaying numbers as text, concatenating them with other strings, or storing them in string-based data structures. 

Int to String in C++

In this article, we will learn several methods to convert an int to a string in C++, including using the to_string() function, stringstream, sprintf(), & boost lexical_cast.

Using to_string()

One of the simplest & most straightforward ways to convert an int to a string in C++ is by using the to_string() function. This function is part of the <string> library & provides a convenient way to convert various data types, including integers, to their string representations.

Example

  • C++

C++

#include <iostream>

#include <string>

int main() {

   int num = 42;

   std::string str = std::to_string(num);

   std::cout << "The integer " << num << " converted to a string is: " << str << std::endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

In this code snippet, we declare an integer variable num & assign it the value 42. We then use the std::to_string() function to convert num to a string & store the result in the str variable. Finally, we print out the original integer value & its string representation using std::cout.

The output of this program will be:

The integer 42 converted to a string is: 42


Note : The to_string() function is available in C++11 & later versions. It provides a simple & efficient way to convert integers to strings without the need for additional libraries or complex code.

Using stringstream

Another popular method for converting an int to a string in C++ is by using the stringstream class from the <sstream> library. stringstream allows you to perform input & output operations on strings, making it a versatile tool for type conversions.

Example

  • C++

C++

#include <iostream>

#include <sstream>

#include <string>

int main() {

   int num = 42;

   std::stringstream ss;

   ss << num;

   std::string str = ss.str();

   std::cout << "The integer " << num << " converted to a string is: " << str << std::endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

In this code, we create an instance of the std::stringstream class called ss. We then use the << operator to insert the integer value num into the stringstream. This converts the integer to its string representation.

To retrieve the string from the stringstream, we call the str() member function, which returns the contents of the stringstream as a string. We store this string in the str variable.

Finally, we print out the original integer value & its string representation using std::cout.

The output of this program will be the same as the previous example:

The integer 42 converted to a string is: 42


Note : stringstream provides more flexibility compared to to_string() as it allows you to perform additional formatting operations on the string if needed. It is a good choice when you need to convert multiple values or perform complex string manipulations.

Using sprintf() function

The sprintf() function, which is part of the <cstdio> library, is another way to convert an int to a string in C++. It allows you to format a string using a format specifier & store the result in a character array.

Example 

  • C++

C++

#include <iostream>

#include <cstdio>

int main() {

   int num = 42;

   char str[20];

   sprintf(str, "%d", num);

   std::cout << "The integer " << num << " converted to a string is: " << str << std::endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code


In this code, we declare an integer variable num & assign it the value 42. We also declare a character array str with a size of 20 to store the resulting string.

We then use the sprintf() function to convert the integer to a string. The first argument of sprintf() is the destination character array where the formatted string will be stored. The second argument is the format specifier, which in this case is "%d", indicating that we want to format an integer. The third argument is the integer value num that we want to convert.

After the conversion, the resulting string is stored in the str array. Finally, we print out the original integer value & its string representation using std::cout.

The output of this program will be the same as the previous examples:

The integer 42 converted to a string is: 42


Note : sprintf() can be useful when you need more control over the formatting of the resulting string. It allows you to specify the width, precision, & other formatting options using format specifiers.

Using boost lexical_cast

The Boost library provides a convenient function called lexical_cast that allows you to convert between different data types, including converting an int to a string. To use lexical_cast, you need to include the <boost/lexical_cast.hpp> header file.

Example 

  • C++

C++

#include <iostream>

#include <string>

#include <boost/lexical_cast.hpp>

int main() {

   int num = 42;

   std::string str = boost::lexical_cast<std::string>(num);

   std::cout << "The integer " << num << " converted to a string is: " << str << std::endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code


In this code, we include the necessary headers, including <boost/lexical_cast.hpp> for using the lexical_cast function.

We declare an integer variable num & assign it the value 42. To convert num to a string, we use boost::lexical_cast<std::string>(num). The lexical_cast function takes the integer value as an argument & returns its string representation.

We store the resulting string in the str variable. Finally, we print out the original integer value & its string representation using std::cout.

The output of this program will be the same as the previous examples:

The integer 42 converted to a string is: 42


Note : boost::lexical_cast provides a simple & generic way to convert between different types. It handles the conversion internally & throws an exception if the conversion fails.

Note that to use the Boost library, you need to have it installed & properly linked to your project.

Frequently Asked Questions

What is the main advantage of using to_string() over other methods?

The to_string() function is straightforward & highly readable, making it ideal for simple conversions without the need for formatting.

Can stringstream handle types other than integers?

Yes, stringstream can convert various data types, including floating-point numbers & custom classes (with properly overloaded operators), offering versatile type handling.

Is sprintf() safe to use for type conversion in modern C++?

While sprintf() is powerful & flexible, it lacks the type safety of to_string() & stringstream. Misuse can lead to buffer overflows, so it's recommended to use it with caution or prefer safer alternatives in modern C++ code.

Conclusion 

In this article, we have learned several ways to convert an int to a string in C++. We discussed methods like using the to_string() function, stringstream, sprintf(), & boost::lexical_cast. Each method has its own advantages & use cases. to_string() is simple & straightforward, stringstream offers flexibility for complex string manipulations, sprintf() provides formatting options, & boost::lexical_cast is a generic solution from the Boost library.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass