Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
2 Answers
- 1 decade agoFavorite Answer
conversion of an int to a string in c++, using a stringstream object :
method 1:
#include <iostream>
#include <sstream> // Required for stringstreams
#include <string>
std::string IntToString ( int number )
{
std::ostringstream oss;
// Works just like cout
oss<< number;
// Return the underlying string
return oss.str();
}
int main()
{
int number = 12345;
std::string result = IntToString ( number );
// Now we can use concatenation on the number!
std::cout<<"~~{" + result + "}~~\n";
}
method 2 : it will display as true r false
#include <sstream>
#include <string>
using namespace std;
bool StringToInt(const string &s, int &i);
int main(void)
{
string s1 = "12";
string s2 = "ZZZ";
int result;
if (StringToInt(s1, result))
{
cout << "The string value is " << s1
<< " and the int value is " << result << endl;
}
else
{
cout << "Number conversion failed" <<endl;
}
if (StringToInt(s2, result))
{
cout << "The string value is " << s2
<< " and the int value is " << result << endl;
}
else
{
cout << "Number conversion failed on " <<s2 <<endl;
}
return(0);
}
bool StringToInt(const string &s, int &i)
{
istringstream myStream(s);
if (myStream>>i)
return true;
else
return false;
/*
* Program output:
The string value is 12 and the int value is 12
Number conversion failed on ZZZ
*
*/
method 3 : The simpest method of all
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
string itos(int i)// convert int to string
{
stringstream s;
s << i;
return s.str();
}
int main()
{
int i = 127;
string ss = itos(i);
const char* p = ss.c_str();
cout << ss << " " << p << "\n";
}
- 1 decade ago
#include<stdlib.h>
...
for integer
itoa(int n,char* s);
for long
ltoa(long int n, char*s);