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*)'
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);
试试这样:
long i = atol(item.c_str());
使用std :: stol <字符填充空格>
Use a string stream.
#include <sstream>
// code...
std::string text;
std::stringstream buffer(text);
long var;
buffer >> var;
如果您无法访问C ++ 11,并且可以使用boost库,则可以考虑以下选项:
long l = boost::lexical_cast< long >( item );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.