Javatpoint Logo
Javatpoint Logo

C++ int to string

There are three ways of converting an integer into a string:

C++ int to string
  • By using stringstream class
  • By using to_string() method
  • By using boost.lexical cast

Conversion of an integer into a string by using stringstream class.

The stringstream class is a stream class defined in the header file. It is a stream class used to perform the input-output operations on string-based streams.

The following are the operators used to insert or extract the data:

  • Operator >>: It extracts the data from the stream.
  • Operator <<: It inserts the data into the stream.

Let's understand the concept of operators through an example.

  • In the below statement, the << insertion operator inserts the 100 into the stream.
                          stream1 << 100;
  • In the below statement, the >> extraction operator extracts the data out of the stream and stores it in 'i' variable.
                          stream1 >> i;

Let's understand through an example.

Output

C++ int to string

In the above example, we created the k variable, and want to convert the value of k into a string value. We have used the stringstream class, which is used to convert the k integer value into a string value. We can also achieve in vice versa, i.e., conversion of string into an integer value is also possible through the use of stringstream class only.

Let's understand the concept of conversion of string into number through an example.

Output

C++ int to string

Conversion of an integer into a string by using to_string() method.

The to_string() method accepts a single integer and converts the integer value or other data type value into a string.

Let's understand through an example:

Output

C++ int to string

Conversion of an integer into a string by using a boost.lexical cast.

The boost.lexical cast provides a cast operator, i.e., boost.lexical_cast which converts the string value into an integer value or other data type value vice versa.

Let's understand the conversion of integer into string through an example.

Output

C++ int to string

In the above example, we have converted the value of 'i' variable into a string value by using lexical_cast() function.

Let's understand the conversion of string into integer through an example.

Output

C++ int to string

In the above example, we have converted the string value into an integer value by using lexical_cast() function.

Next TopicC++ Tutorial




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA