Hey,
I've recently been learning some C# and it's been really helpful that every type has a .ToString() method inside their class and I was wondering if there was any equivalent in C++ apart from the string stream or itoa/atoi, I was thinking of creating a base class which has a method like this and making every type inherit from that one class but that would take a while!!
I'm sorry but did any of you even read my post?? I appreciate the answers given but my original post asked whether there is a way of changing an int to a string (or the other way around) WITHOUT using the atoi/itoa or stringstream
#include <iostream>
int main ()
{
using std::cout;
using std::cin;
using std::endl;
char outputString[4];
outputString[3]=0;
int temp;
cout << "Enter an int up to three digits long" << endl;
cin >> temp;
int a = temp%10;
outputString[2]=a+48;
temp = temp - a;
temp = temp/10;
a = temp%10;
outputString[1]=a+48;
temp = temp - a;
temp = temp/10;
a = temp%10;
outputString[0]=a+48;
cout << outputString;
return 0;
}
Boost's lexical_cast is often used for this. You can also define a VCL-style IntToStr specifically for ints in global namespace as a shortcut (which can just call lexical_cast<string>).
I'm sorry but did any of you even read my post?? I appreciate the answers given but my original post asked whether there is a way of changing an int to a string (or the other way around) WITHOUT using the atoi/itoa or stringstream
I'm sorry I tried to give some help -- I didn't realize that it would be taken with such cheek.
C++ is not C#. If you want C#, then go use C#.
In C++, the toString() stuff is as I said:
All the conversion stuff is in the stream classes... Use a stringstream for it
Again, the streams design is how C++ does toString(). In conclusion, if you want to do toString() stuff, use the STL streams classes.