将 C++ 字符串变量转换为 long

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11776210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:31:23  来源:igfitidea点击:

Convert C++ string variable to long

c++stringlong-integer

提问by kunal18

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:

它在运行时被初始化。我需要将其转换为long。怎么做?我试过 atol() 和 strtol() 但我总是分别得到以下 strtol() 和 atol() 错误:

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*)'

回答by Ivan Kruglov

Try like this:

像这样尝试:

long i = atol(item.c_str());

回答by yuri kilochek

Use std::stol< characters to fill space >

使用std::stol< 字符填充空间 >

回答by ApprenticeHacker

Use a string stream.

使用字符串流。

#include <sstream>

// code...
std::string text;
std::stringstream buffer(text);
long var;
buffer >> var;

回答by Daniele Pallastrelli

If you don't have access to C++11, and you can use the boost library, you can consider this option:

如果你无权使用C++11,并且可以使用boost库,可以考虑这个选项:

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