Convert int to string easily in C++

Hello, Coders! In this tutorial, we will learn various ways to convert integer to string in C++.

Let’s discuss the following conversion methods:

  • stringstream class
  • to_string() method
  • boost.lexical cast

stringstream Class in C++

The stringstream class also known as input and output string stream belongs to a Stream Class.  This class is helpful to perform various types of operations on strings.

  • Extraction of the data is performed by << operator.
int output = 86;
stream << output;

 

  • Insertion of the data is performed by >> operator.
int input;
stream >> input;

 

Example:

#include<iostream>

#include<sstream>

using namespace std;

int main() {
  int integer_val;
  cout << "Give an Integer value:";
  cin >> integer_val;

  stringstream ss;
  ss << integer_val;
  string string_val;
  ss >> string_val;

  cout << "The given integer value is " << integer_val << endl;
  cout << "The String value of the Integer is " << string_val << endl;
}

Output:

Give an Integer value:86
The given integer value is 86
The String value of the Integer is 86

to_string() Method in C++ to convert int to string

In C++ the to_string( ) method is used to convert any basic data type value into a string.

Syntax:

string str = to_string(val);
//Where val = any type of value i.e int,float,etc.

Example:

#include <iostream>

#include<string>

using namespace std;

int main() {
  int integer_val;
  cout << "Give an Integer value:";
  cin >> integer_val;
  string string_val = to_string(integer_val);

  cout << "The given integer value is " << integer_val << endl;
  cout << "The String value of the Integer is " << string_val << endl;
}

Output:

Give an Integer value:-15
The given integer value is -15
The String value of the Integer is -15

boost.lexical Cast

The boost.lexical cast provides a cast operator which converts any data type value to a string and vice versa. It is an alternative to functions like stoi(), stood() and to_string().

Note: Before using this method install Boost Library for C++ Compiler.

Syntax:

string str = boost::lexical_cast < string > (val);
//Where val = any type of value i.e int,float,etc.

Example:

#include <iostream>

#include <boost/lexical_cast.hpp>

using namespace std;

int main() {
  int integer_val;
  cout << "Give an Integer value:";
  cin >> integer_val;
  
  string string_val = boost::lexical_cast < string > (integer_val);
  
  cout << "The given integer value is " << integer_val << endl;
  cout << "The String value of the Integer is " << string_val << endl;

}

Output:

Give an Integer value:48
The given integer value is 48
The String value of the Integer is 48

Hope this article has helped you understand the concept of converting the integer value to string in C++.

Happy Coding!!

You can also read, Conversion of string to integer in C++

Leave a Reply

Your email address will not be published. Required fields are marked *