Are there any int to string conversion functions?
Printable View
Are there any int to string conversion functions?
itoa(int,char*,int)
the first int is the integer to change to a string
the char* is where the string is stored
the second int is the radix, or the base of the the first int.
base? what do you mean?
Decimal is base 10, hex is base 16, binary is base 2, etc.
itoa is non-standard.
Use a stringstream
In the new faq thread on the General Disucssions board,
Code:#include <sstream> //this header automatically includes iostream and is needed for ostringstream
#include <string>
using namespace std;
string IntToString(int num); //this will be our converter function
int main(void)
{ int number=5;
string result=IntToString(number);
cout<<result<<endl;
cin.get();
return 0;
}
string IntToString(int num)
{ ostringstream myStream; //creates an ostringstream object
myStream<<num<<flush;
/*outputs the number into the string stream and then flushes
the buffer (makes sure the output is put into the stream)*/
return myStream.str(); //returns the string form of the stringstream object
}
Code:template <typename T>
std::string ToString(const T& number)
{
std::ostringstream os;
os << number;
return os.str();
}
True, but two things...
Is a beginner gonna know how to use templates?
Are they needed in this instance?
The answer to both is probably no.
Well, if the only thing being converted are int's, then no, templates aren't necessary at all, but still is good to know what your options are, don't you think?
One should aim at making code reusable, and this was just a very humble example.