// to_string example
#include <iostream> // std::cout
#include <string> // std::string, std::to_string
int main ()
{
std::string pi = "pi is " + std::to_string(3.1415926);
std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
std::cout << pi << '
';
std::cout << perfect << '
';
return 0;
}
/*
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
Parameters :
val - Numerical value.
Return Value :
A string object containing the representation of val as a sequence of characters.
*/
// CPP code to find a digit in a number
// using std::tostring
#include <bits/stdc++.h>
using namespace std;
// Driver code
int main()
{
// Converting number to string
string str = to_string(9954);
// Finding 5 in the number
std::cout << "5 is at position " << str.find('5') + 1;
}
int i=11;
string str= to_string(i);
- Writing your own conversion function, the simple:
template<class T> string toString(const T& x) {
ostringstream ss;
ss << x;
return ss.str();
}
- Since C++11 you can also use the std::to_string:
string s = to_string(0x12f3); // after this the string s contains "4851"