Data type conversion is a common process that is widely used in programming. There are several cases where you need to convert a variable of one data type to another. You can do the conversion of data types in two ways: Implicit type conversion (done by the compiler) and Explicit type conversion (done manually). Most of the programming languages provide inbuilt methods to perform explicit type conversion. 

Converting data from an integer format to a string allows you to perform various string operations on the data. Sometimes arithmetic operations become a tedious task compared to string operations. For instance, consider the following example to print the current date.

Using String Operation:

    string year = "2021";

    cout << "Today's date is: 31/05/" << year.substr(2);

Output: 

Today's date is: 31/05/21

Using Arithmetic Operation:

    int year = 2021;

    int formattedYear = year - 2000;

    cout << "Today's date is: 31/05/" << formattedYear;

Output: 

Today's date is: 31/05/21

In the above example, the first method that uses a string operation to print the current date is more convenient than the second method which uses an arithmetic operation.

In this article, you will explore how you can convert an integer into a string in C++. 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

How to Convert Int to String in C++

There are three different ways in which you can perform conversion of an int to string in C++. In this section, you will look into all these three methods in detail.

1. Using the Stringstream Class

The stringstream class allows input/output operations on streams based on strings. It can perform parsing in various ways. The stringstream class is included in the “sstream” header file. It includes the following basic methods in the stringstream class:

  • Operator “>>”: The “>>” operator in the stringstream class is used to read or extract formatted data from a stream object
  • Operator “<<”: The “<<” operator in the stringstream class is used to add formatted data into a stream object
  • str(): The str() method of the stringstream class is used to assign or retrieve values of the underlying string object
  • clear(): The clear() method of the stringstream class is used to clear the contents of the stream

The “<<” and “>>” operators can convert int to string in C++. The syntax to insert and extract data using these operators is:

    // declare a stream object

    stringstream string_object_name;

    // insert operation

    string_object_name << 50;

    // extract operation

    string_object_name >> my_var;

Description of the syntax

  • string_object_name: This is the name of the stringstream object that was declared to perform the input/output operations on strings.
  • “<<”: This operator inserts the value on the right-hand side to the stringstream object.
  • “>>”: This operator extracts the value of the stringstream object and stores it in a string variable on the right-hand side.

Example

Input:

str_s << 20

            str_s >> my_string

Output: 20 

Explanation:

You insert the integer 20 into the string object str_s and extracted it to a string variable my_str, which eventually converts the integer 20 into the string “20”.

The following example illustrates the working of stringstream class to convert int to string in C++:

#include <iostream>

#include <sstream>    // header file for stringstream

using namespace std;

int main()

{

    // initialize an integer

    int num = 20;

    // applying the stringstream class

    // declare a stream object

    stringstream stream;

    stream << num;

    // initializing a string

    string str;

    stream >> str;

    cout << "\n"

         << "Value of num is : " << num << "\n";

    cout << "String representation of the num after applying stringstream is : " << str;

return 0; 

}

Int_to_String_C_Plus_Plus_1.

In the above example, it converts the integer 20 into the string “20”. The stream object performs insertion and extraction operations using the “<<” and “>>” operators. The integer 20 is first inserted into the object stream and then extracted to a string variable str.

2. Using the to_string() Method

The next method in this list to convert int to string in C++ is by using the to_string() function. This function is used to convert not only the integer but numerical values of any data type into a string. 

The syntax of the to_string() function is:

string to_string (int num);

string to_string (long num);

string to_string (long long num);

string to_string (unsigned num);

string to_string (unsigned long num);

string to_string (unsigned long long num);

string to_string (float num);

string to_string (double num);

string to_string (long double num);

Description of the syntax

  • The to_string() method is included in the header file of the class string, i.e., <string> or <cstring>.
  • This function takes a numerical value as a parameter that has to be converted into a string. This numerical value can be of any data type, including integer, float, double, long double, etc. 

Return Value

This function returns a string object corresponding to the value passed as an argument.

Example

Input: x = 10;

            to_string(x);

Output: 10 

Explanation:

The variable holding an integer value i.e. 10 is passed to the to_string() method which returns a corresponding string “10”.

The following example illustrates the working of to_string() function in C++:

#include <iostream>

#include <string> // header file for string

using namespace std; 

int main()

{

    // initializing integers

    int num1 = 21;

    int num2 = 2122;

    int num3 = 212232; 

    // Converting int to string

    string str1 = to_string(num1); 

    // Converting int to string

    string str2 = to_string(num2);

    // Converting int to string

    string str3 = to_string(num3);

    // print the converted strings

    cout << "String representation of num1: " << str1 << '\n';

    cout << "String representation of num2: " << str2 << '\n';

    cout << "String representation of num3: " << str3 << '\n';

    return 0;

}

 Int_to_String_C_Plus_Plus_2

In the above example, there are three integers, num1, num2, and num3. To convert them into a string, you have passed each integer to the to_string() function and get their string representation. Note that to use the functionality of the string class, you have to add the <string> header file.

Preparing Your Blockchain Career for 2024

Free Webinar | 5 Dec, Tuesday | 9 PM ISTRegister Now
Preparing Your Blockchain Career for 2024

3. Using boost::lexical_cast

The boost::lexical_cast method is another method to convert an integer into a string. This function is defined in the library “boost/lexical_cast.hpp” and can perform interconversions of different data types including float, integer, double, and string.

Note: You need to install the Boost libraries first, before executing this method to convert int to string in C++.

The syntax of the boost::lexical_cast method is:

boost::lexical_cast<data-type>(argument)

Description of the Syntax

  • data-type: This is the type in which the argument needs to be converted. To convert an integer to a string, you should specify the data type as a string.
  • argument: This is the value that needs to be converted. To convert an integer to a string, the argument should be an integer value.

Example

Input: num = 50

            boost::lexical_cast<string> (num)

Output: 50 

Explanation:

It passes the integer 50 as an argument to the lexical_cast operator, which converts this integer into the corresponding string “50”.

The following example illustrates the working of boost::lexical_cast to convert int to string in C++:

#include <bits/stdc++.h>

#include <boost/lexical_cast.hpp>

using namespace std;

int main()

{

    //initialize the integer

    int num = 50; 

    // convert int to string

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

    // print the converted string

    cout << "The string representation of the integer num is :" << str << "\n";

    return 0;

}

Int_to_String_C_Plus_Plus_3.

In the above example, the integer 50 is converted into a string by passing it as an argument to the lexical_cast operator. 

How to Declare and Initialize Strings in C++?

In C++, strings are objects of the std::string class that allow you to store and manipulate sequences of characters.

  • To declare a string variable, you can use the following syntax:

std::string str;  // declare an empty string variable

  • To initialize the string with a value, use one of the following methods:

std::string str1 = "Hello, world!"; // initialize a string with a string literal

std::string str2("This is a C++ string."); // initialize a string with a constructor

std::string str3 {'A', 'B', 'C'}; // initialize a string with a list of characters

  • To concatenate strings using the + operator, use the following syntax:

std::string str4 = "Hello" + ", " + "world" + "!"; // concatenate strings

  • Converting an Integer to a String 
  • Using to_string function

In C++, you can use the to_string function to convert an integer to a string. This function is a member of the std namespace, and it takes an integer value as its argument and returns a string.

int num = 123;

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

Here, the to_string() method is used to convert the integer value 123 into a string.

The to_string function is part of the C++11 standard, so it may not work on older compilers that do not support this standard.

  • Using sprintf( ) function

We can use the sprintf function to convert an integer to a string:

int num = 123;

char buffer[10];

std::sprintf(buffer, "%d", num);

std::string str(buffer);

The sprintf function is used to write the integer value 123 to a character array buffer, and then the character array is converted to a string using the std::string constructor

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

When and Why Do We Need to Convert Int to String in C++?

In C++, an int is a data type that stores integer values, while a string is a data type that stores text-based values. It is sometimes necessary to convert an int to a series when the user requires a string representation of a numerical value. Conversion of an int to a string allows the user to perform string-specific operations on the newly created series, such as concatenation or formatting. Furthermore, an int-to-string mutation is beneficial when the user needs to save an int as text in a file or when displaying an int to the console for visual purposes.

Converting integers to strings in C++ is a common task and can be achieved using the stringstream class, which provides a stream-based solution to convert numbers to strings. The basic idea behind this class is to create a stream of characters and then add the numbers as if they were strings on their own. Once the conversion is complete, the resulting stream can be read as a string. This approach is helpful when we need to convert an integer into a line and pass it as a parameter to a function or store it in a data structure.

Cpp_Int_to_string_1

Output:

Cpp_Int_to_string_output.

Examples for Various Data Types in C++

  • Integer Data Type:

int age = 25;

In this example, the age variable is declared as an integer and initialized with the value of 25.

  • Floating-Point Data Type:

float pi = 3.14;

In this example, the pi variable is declared as a floating-point variable and initialized with the value of 3.14.

  • Double Data Type:

double salary = 10000.50;

In this example, the salary variable is declared as double and initialized with the value of 10000.50.

  • Character Data Type:

char grade = 'A';

In this example, the grade variable is declared as a character and initialized with the value of 'A'.

  • Boolean Data Type:

std::string name = "John";

In this example, the name variable is declared as a string and initialized with the value of "John".

  • Long Data Type:

long population = 1000000L;

In this example, the population variable is declared as long and initialized with the value of 1000000L.

  • Unsigned Data Type:

unsigned int count = 10;

In this example, the count variable is declared as an unsigned integer and initialized with the value of 10.

Final Thoughts!

To sum up quickly, in this article, you have learned about the importance of data-type or type conversions in C++. You saw three different methods to convert an integer data type to a string data type in C++. Converting an integer to a string data type allows you to modify the digits in an integer and perform several other operations on an integer which could have been possible only on a string. You understood the stringstream class, to_string() method, and the lexical_cast method to convert integer data types to string.

If you want to learn more about such fundamental concepts in C++, you should definitely check out our complete guide on C++ for beginners

Why stop here? If you want to learn more about various other tools, frameworks, and programming languages, you can take up any of our free online courses taught by industry experts with years of knowledge and experience. Check out these free online courses.

It also makes sense to learn one of the most trending and in-demand software development skills - Full Stack Web Development. Simplilearn makes it a whole lot easier for you. You can take up the 9-month mentor-led Full Stack Web Development course. At the end of this course, you will have learned several trending tools and frameworks including Java and its frameworks such as Hibernate, Spring, JPA, etc., DevOps, Agile, front-end technologies such as HTML, CSS, JS, Servlets, etc.

If you have any queries related to this article on “Int to String in C++” or any other suggestions for us, please feel free to drop a comment in the comment box and our experts will get back to you at the earliest.

Happy Learning!

FAQs

1. How to convert int into a string?

There are various methods we can employ to convert an integer into a string in c++:

a) Using the Stringstream Class
b) Using the to_string() Method
c) Using boost::lexical_cast

2. What is to_string in C++?

to_string is a built-in function in C++ that allows converting numerical data types, such as integers or floating-point numbers, into their corresponding string representations.

3. How to convert int to string in C++ using Sstream?

To convert an integer to a string using Sstream, follow these steps:

a) Include the <sstream> header to use the Sstream library.
b) Create an std::stringstream object.
c) Use the << operator to insert the integer into the stringstream.
d) Extract the string using the str() method of the stringstream.

4. What is itoa and atoi in C++?

itoa: itoa is a C Standard Library function used to convert an integer to a string. It is not part of the C++ Standard Library, but it is available in many C++ implementations due to its widespread use.

atoi: atoi is a C Standard Library function used to convert a string to an integer. Like itoa, it is not part of the C++ Standard Library but is available in many C++ implementations.

5. How do you use Itoa ()?

To use itoa() to convert an integer to a string in C++, follow these steps:

a) Include the <cstdlib> header to use the C Standard Library function.
b) Declare a character array (char buffer) to store the resulting string.
c) Call the itoa() function, passing the integer, the character array (buffer), and the base (usually 10 for decimal).
d) The integer will be converted and stored as a string in the character array.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 24 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449