Convert C++ string variable to long

匿名 (未验证) 提交于 2019-12-03 03:08:02

问题:

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


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