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. 

Unleash Your Career as a Full Stack Developer!

Full Stack Developer - MERN StackEXPLORE COURSE
Unleash Your Career as a Full Stack Developer!

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;
Accelerate your career as a skilled MERN Stack Developer by enrolling in a unique Full Stack Developer - MERN Stack Master's program. Get complete development and testing knowledge on the latest technologies by opting for the MERN Stack Developer Course. Contact us TODAY!

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.

Advance Your MERN Stack Career in 6 Months!

Full Stack Developer - MERN StackEXPLORE COURSE
Advance Your MERN Stack Career in 6 Months!

Example

Input:str_s << 20            str_s >> my_stringOutput: 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 stringstreamusing 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.

Become a Full Stack Developer in Just 6 Months!

Full Stack Developer - MERN StackEXPLORE COURSE
Become a Full Stack Developer in Just 6 Months!

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.

Get the Coding Skills You Need to Succeed

Full Stack Developer - MERN StackExplore Program
Get the Coding Skills You Need to Succeed

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 stringusing 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. 

4. Using the sprintf() function

The ‘sprintf()’ function in C formats and stores a series of characters and values in the string. It is part of the standard input/output library. It is commonly used to create formatted strings without printing them directly to the console, providing more control over the string output.

Description of the Syntax

The syntax of the ‘sprintf()’ function is as follows:

int sprintf(char *str, const char *format, ...);

‘str’: Pointer to the array where the resulting C-string is stored.

‘format’: C-string that contains a format string that follows the same specifications as the format in ‘printf()’.

‘...’: Additional arguments specifying the data to be formatted.

The function returns the total number of characters written, excluding the null-character appended at the end of the string.

Example

Here is an example of using sprintf():

#include <stdio.h>

int main() {
    char buffer[50];
    int age = 30;
    double salary = 12345.67;

    sprintf(buffer, "Age: %d, Salary: %.2f", age, salary);
    printf("%s\n", buffer);

    return 0;
}

Explanation

In this example, we first include the standard I/O library with ‘#include <stdio.h>’. We then declare a character array ‘buffer’ to hold the formatted string, and two variables ‘age’ and ‘salary’ to store the data we want to format.

The ‘sprintf()’ function is called with ‘buffer’ as the destination string, and a format string ‘"Age: %d, Salary: %.2f"’. This format string includes two format specifiers: ‘%d’ for the integer ‘age’ and ‘%.2f’ for the floating-point number ‘salary’ formatted to two decimal places.

The sprintf() function formats the ‘age’ and ‘salary’ values according to the specified format and stores the resulting string in ‘buffer’. Finally, the formatted string is printed to the console using ‘printf()’, displaying: ‘Age: 30, Salary: 12345.67’.

This example demonstrates how ‘sprintf()’ can be used to create formatted strings for various types of data without printing them directly to the console, offering flexibility in string handling.

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 literalstd::string str2("This is a C++ string."); // initialize a string with a constructorstd::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.

Accelerate your career as a skilled MERN Stack Developer by enrolling in a unique Full Stack Developer - MERN Stack Master's program. Get complete development and testing knowledge on the latest technologies by opting for the MERN Stack Developer Course. Contact us TODAY!

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: 16 Dec, 2024

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 27 Nov, 2024

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 18 Dec, 2024

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449