C++ Convert Int to String
In fact, the conversion of numbers to strings or vice versa represents a significant paradigm change. We often need to convert a number to a string or a string to a number in general, or more especially in competitive programming. But we can't do so fluently because we have inadequate knowledge of some crucial skills. In this article, a few approaches to doing this work are discussed.
Number to String Conversion in C++:
The three main ways to change a number into a string are as follows:
- By using string Stream
- By using to_string()
- By using boost lexical cast
First approach: String Streams:
In this method, a stream object is declared that first inserts a number as a stream into an object before using "str()" to carry out the internal conversion of a number to a string.
C++ Program:
#include<iostream> //header files
#include <sstream>
#include <string>
using namespace std;
int main()
{
//initializing an integer
int value = 2001;
ostringstream strng1;
strng1 << value;
// changing number into string
string s1 = strng1.str();
//printing the string
cout << " The freshly created number string is: ";
cout << s1 << endl;
return 0;
}
Output:
The freshly created number string is: 2001
Time Complexity: O(n)
Space Complexity: O(n)
Second approach: to_string():
The to_string() method takes a number, which can be of any data type, and returns it as the specified string.
C++ Program:
#include <iostream> //header files
#include <string>
using namespace std;
int main()
{
//initializing an integer number
int inval = 25;
//initializing a floating number
float flval = 15.03;
//changing int to string
string strng_i= to_string (inval);
// changing float to string
string strng_f = to_string (flval);
// printing the converted strings
cout << "In string, the integer is: ";
cout << strng_i << endl;
cout << "In string, the float is: ";
cout << strng_f << endl;
return 0;
}
Output:
In string, the integer is: 25
In string, the float is: 15.030000
Time Complexity: O(n)
Auxiliary Space: O(n)
Third approach: Boost Lexical Cast:
Similar to how string conversion works, the "lexical cast()" method stays the same, but the argument list changes when using "boost lexical cast," becoming "lexical_cast(num_var)".
C++ Program:
#include <boost/lexical_cast.hpp> //header files
#include <iostream>
#include <string>
using namespace std;
int main()
{
//initializing a floating number
float fl_val = 17.6;
//initializing an integer number
int in_val = 21;
// changing float to string
string strng_f = boost::lexical_cast<string>(fl_val);
//changing int to string
string strng_i = boost::lexical_cast<string>(in_val);
// printing the converted strings
cout << "In string, the float is: ";
cout << strng_f << endl;
cout << "In string, the integer is: ";
cout << strng_i << endl;
return 0;
}
Output:
In string, the float is: 17.6
In string, the integer is: 21
Time Complexity: O(n)
Auxiliary Space: O(n)