Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert C++ string variable to long

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*)'
like image 460
kunal18 Avatar asked Aug 02 '12 11:08

kunal18


People also ask

Can you convert a string to a long?

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.

What is strtol () in C?

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.

Is there an itoa in C?

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.

What is Endptr in C?

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.


2 Answers

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

like image 117
log0 Avatar answered Oct 17 '22 19:10

log0


Try like this:

long i = atol(item.c_str());
like image 24
Ivan Kruglov Avatar answered Oct 17 '22 18:10

Ivan Kruglov