The Ultimate Guide to Understand Int to String in C++

Int to String in C++

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

Stand Out From Your Peers this Appraisal Season

Start Learning With Our FREE CoursesEnroll Now
Stand Out From Your Peers this Appraisal Season

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

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

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. 

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

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!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.