可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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*)'
回答1:
Try like this:
long i = atol(item.c_str());
回答2:
回答3:
Use std::stol < characters to fill space >
回答4:
Use a string stream.
#include <sstream> // code... std::string text; std::stringstream buffer(text); long var; buffer >> var;
回答5:
If you don't have access to C++11, and you can use the boost library, you can consider this option:
long l = boost::lexical_cast< long >( item );