Convert C++ string variable to long

心不动则不痛 提交于 2019-12-06 01:26:52

问题


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:


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




回答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 );


来源:https://stackoverflow.com/questions/11776210/convert-c-string-variable-to-long

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!