I have a variable:
string item;
It gets initialized at run-time. I need to convert it to long. How to do it? I have tried atol() and strtol() but I always get following error for strtol() and atol() respectively:
cannot convert 'std::string' to 'const char*' for argument '1' to 'long int strtol(const char*, char**, int)'
cannot convert 'std::string' to 'const char*' for argument '1' to 'long int atol(const char*)'
There are many methods for converting a String to a Long data type in Java which are as follows: Using the parseLong() method of the Long class. Using valueOf() method of long class. Using constructor of Long class.
The strtol library function in C converts a string to a long integer. The function works by ignoring any whitespace at the beginning of the string, converting the next characters into a long integer, and stopping when it comes across the first non-integer character.
The itoa (integer to ASCII) function is a widespread non-standard extension to the standard C programming language. It cannot be portably used, as it is not defined in any of the C language standards; however, compilers often provide it through the header <stdlib.
endptr − This is the reference to an object of type char*, whose value is set by the function to the next character in str after the numerical value. base − This is the base, which must be between 2 and 36 inclusive, or be the special value 0.
c++11:
long l = std::stol(item);
http://en.cppreference.com/w/cpp/string/basic_string/stol
C++98:
char * pEnd;.
long l = std::strtol(item.c_str(),&pEnd,10);
http://en.cppreference.com/w/cpp/string/byte/strtol
Try like this:
long i = atol(item.c_str());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With