Convert C ++ string variable to long

I have a variable:

string item; 

It is initialized at runtime. I need to convert it to long. How to do it? I tried atol () and strtol (), but I always get the 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*)' 
+6
source share
5 answers

Try it like this:

 long i = atol(item.c_str()); 
+16
source

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

+16
source

Use std :: stol <characters to fill in the blank>

+4
source

Use a stream of strings.

 #include <sstream> // code... std::string text; std::stringstream buffer(text); long var; buffer >> var; 
+4
source

If you do not have access to C ++ 11, and you can use the boost library, you can consider this option:

 long l = boost::lexical_cast< long >( item ); 
+1
source

Source: https://habr.com/ru/post/921938/


All Articles