int to string in C++

Written by

Garvit Gulati

Many times we need to convert an int value to a string for a number of purposes. To do this, we may use any of the following methods:

  1. Using string stream
  2. Using to_string() function

# Using string stream

String streams are similar to iostream and fstream but they allow us to perform I/O operations on string. Just like fstream, it has three main classes:

  1. stringstream: for both input and output
  2. ostringstream: for only output
  3. istringstream: for only input

To convert an int to a string using stringstream, we first create an output stream object which inserts a number as a stream into the object and then, with the help of str() function of stringstream, the number is internally converted to a string.

Implementation

#include <iostream>
#include <sstream>	//for string stream
#include <string>	//for strings
using namespace std;

int main()

{
	int num = 10;

	ostringstream ob;

	ob << num;	//pushing num into output string stream

	string str;

	str = ob.str();	//conversion of num to string

	cout << "String is:" << str;

	return 0;

}

Output

String is:10

# Using to_string() function

The C++ string header file provides a function to convert an int to string called to_string(). The function accepts a number of any datatype, int, float, long, double etc, and returns the number in the string.

Implementation:

#include <iostream>
#include <string>   	//for strings
using namespace std;

int main()

{
	int num = 12;

	string str;

	str = to_string(num);

	cout << "String is:" << str;

	return 0;

}

Output

String is:12
int to string in C++