Thursday, July 30, 2009

How do you convert an int to a string in c++?

conversion of an int to a string in c++, using a stringstream object :


method 1:





#include %26lt;iostream%26gt;


#include %26lt;sstream%26gt; // Required for stringstreams


#include %26lt;string%26gt;





std::string IntToString ( int number )


{


std::ostringstream oss;


// Works just like cout


oss%26lt;%26lt; 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%26lt;%26lt;"~~{" + result + "}~~\n";


}








method 2 : it will display as true r false





#include %26lt;sstream%26gt;


#include %26lt;string%26gt;





using namespace std;





bool StringToInt(const string %26amp;s, int %26amp;i);





int main(void)


{


string s1 = "12";


string s2 = "ZZZ";


int result;





if (StringToInt(s1, result))


{


cout %26lt;%26lt; "The string value is " %26lt;%26lt; s1


%26lt;%26lt; " and the int value is " %26lt;%26lt; result %26lt;%26lt; endl;


}


else


{


cout %26lt;%26lt; "Number conversion failed" %26lt;%26lt;endl;


}


if (StringToInt(s2, result))


{


cout %26lt;%26lt; "The string value is " %26lt;%26lt; s2


%26lt;%26lt; " and the int value is " %26lt;%26lt; result %26lt;%26lt; endl;


}


else


{


cout %26lt;%26lt; "Number conversion failed on " %26lt;%26lt;s2 %26lt;%26lt;endl;


}


return(0);


}





bool StringToInt(const string %26amp;s, int %26amp;i)


{


istringstream myStream(s);





if (myStream%26gt;%26gt;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%26lt;iostream%26gt;


#include%26lt;string%26gt;


#include%26lt;sstream%26gt;


using namespace std;





string itos(int i)// convert int to string


{


stringstream s;


s %26lt;%26lt; i;


return s.str();


}





int main()


{


int i = 127;


string ss = itos(i);


const char* p = ss.c_str();





cout %26lt;%26lt; ss %26lt;%26lt; " " %26lt;%26lt; p %26lt;%26lt; "\n";


}

How do you convert an int to a string in c++?
#include%26lt;stdlib.h%26gt;


...


for integer


itoa(int n,char* s);


for long


ltoa(long int n, char*s);


No comments:

Post a Comment