Converting Number to String in C++

C++ : Converting number to string

In this section, we will learn about how to write a program in C++ for converting a number into a string. This is a very common problem which we need to tackle while solving any competitive coding question. Many at times we have to convert a number to a string in order to perform various operations or the result should be of data type string, so we should be familiar with the concept of how to do so.

 

Converting number to string in c++

Converting a Number into String

In C++ programming language, there are mainly three methods for converting a number into string which are as follows :

1. Using string Stream
2. Using to_string()
3. Using boost lexical cast

Method 1 : Using string Stream

In this method, a string stream declares an object which takes a number value initially and then gets converted to a string using str().

Example:

Run

#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main()
{
  int num = 20;
  ostringstream str1;
  str1 << num;
  string p = str1.str();
  cout << "The newly formed string from number is : ";
  cout << p << endl;
  return 0;
}

Output:

The newly formed string from number is : 20

Method 2 : Using to_string()

In this method, the function to_string() takes a number(which can be any data type) and returns the number in the string data type.

Example:

Run

#include<iostream>
#include<string>
using namespace std;
int main()
{
	int i_val = 20;
	float f_val = 30.50;
	string stri = to_string(i_val);
	string strf = to_string(f_val);
	cout << "The integer in string is : ";
	cout << stri << endl;
	cout << "The float in string is : ";
	cout << strf << endl;
	return 0;
}

Output:

The integer in string is : 20
The float in string is : 30.500000

Method 3 : Using boost lexical cast

In this method, the ” lexical_cast() ” function remains the same, but in ‘boost lexical cast‘ time argument list modifies to “lexical_cast(numeric_var). 

Example:

Run

#include<boost/lexical_cast.hpp>
#include<iostream>
#include<string>
using namespace std;
int main()
{
	float f_val = 10.5;
	int i_val = 17;
	string strf = boost::lexical_cast(f_val);
	string stri = boost::lexical_cast(i_val);
	cout << "The float value in string is : ";
	cout << strf << endl;
	cout << "The int value in string is : ";
	cout << stri << endl;
	return 0;
}

Output:

The float value in string is : 10.5
The int value in string is : 17

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription