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.
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.
Using C++ Streams
std::string hello("123");
std::stringstream str(hello);
int x;
str >> x;
if (!str)
{
// The conversion failed.
}
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" );
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);