Possible Duplicate:
How to convert a number to string and vice versa in C++
How do I convert a char array to integer/double/long type -atol() functions?
Possible Duplicate:
How to convert a number to string and vice versa in C++
How do I convert a char array to integer/double/long type -atol() functions?
Either Boost.LexicalCast:
boost::lexical_cast<int>("42");
Or (C++11):
std::stoi("42");
Also, don't use char arrays unless it's interop. Use std::string instead. Also don't ever use ato* functions, even in C, they're broken as designed, as they can't signal errors properly.
std::stoi at SO. I've not seen this before.Writing such a function yourself is a great exercise:
unsigned parse_int(const char * p)
{
unsigned result = 0;
unsigned digit;
while ((digit = *p++ - '0') < 10)
{
result = result * 10 + digit;
}
return result;
}
Of course, you should prefer existent library facilities in real world code.
strlen. I wouldn't call that a security flaw. 2) I am doing unsigned comparison. (digit = *p++ - '0') will produce values bigger than 10 for characters below '0'. 3) Every real world character encoding has consecutive digits, even EBCDIC.<string.h> assumes.x - '0' does not depend on the ASCII table, it only depends on the C++ standard, which I think is acceptable. (reference: §2.3p4 "In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.")template<class In, class Out>
static Out lexical_cast(const In& inputValue)
{
Out result;
std::stringstream stream(std::stringstream::in | std::stringstream::out);
stream << inputValue;
stream >> result;
if (stream.fail() || !stream.eof()) {
throw bad_cast("Cast failed");
}
return result;
}
using it:
int val = lexical_cast< std::string, int >( "123" );
bad_cast constructor taking a C string.std::string(" 123") to this function will work, but passing std::string("123 ") or std::string(" 123 ") will make it throw. Not really robust, IMHO.Do you mean how to convert them to integers? You cannot convert an array of characters into a function on the language level - perhaps you can with some compiler specific inline assembler syntax. For doing a conversion into an integer you can use atoi
int i = atoi("123");`
Or strtol
long l = strtol("123", NULL, 10);
atolfunctions? Like, without using them?