I know that the atoi() function converts a string number to an int equivalent.
Is there a similar function that converts an int number to a string number.
Thanks
Mark S.
Printable View
I know that the atoi() function converts a string number to an int equivalent.
Is there a similar function that converts an int number to a string number.
Thanks
Mark S.
Yep, they're called stringstreams, and they work both ways. There is also a non-standard function known as itoa(), but forget about that. Also, forget about atoi() while you're at it unless you're interested in C. The C++ way is stringstreams.Quote:
Originally Posted by Mark S.
boost::lexical_cast is another choice.
The C pendant to atoi is sprintf. But for C++, stick with the streams or lexical_cast.
>I know that the atoi() function converts a string number to an int equivalent.
That's the theory behind atoi. If you're wise you'll forget it exists. In C it has awful error handling semantics, and strtol (or even sscanf) is the recommended alternative. In C++ there are much better and safer ways to do this (such as stringstreams or the lovely boost::lexical_cast) that are consistent in both directions, unlike the C solution.
Go for string stream! I think there's an itoa() function, unless I'm making that up, but I don't think I am. stringstreams are great!
Here's a nice example that Prelude used the other day to put a number into a string :: http://cboard.cprogramming.com/showp...79&postcount=3 You can Google stringstreams, or there should be a tutorial here somewhere. This is probably helpful http://www.cplusplus.com/ref/iostream/stringstream/
>Here's a nice example that Prelude used the other day to put a number into a string
It's only slightly more complicated and vastly more useful to generalize:
Of course, that's nothing more than a simplified version of what boost::lexical_cast does.Code:#include <sstream>
#include <typeinfo>
namespace jsw {
template <typename T, typename U>
T lexical_cast ( U src )
{
std::stringstream s;
T dst;
if ( !( s << src ) || !( s >> dst ) )
throw std::bad_cast ( "Invalid conversion" );
return dst;
}
}
If you compile as ANSI-compatible, then your compiler will complain that you are. :) It's a non-standard function, although cppreference.com has it.Quote:
I think there's an itoa() function, unless I'm making that up, but I don't think I am.