将字符串转换为长整型

6

我正在尝试将一个字符串转换为长整型。听起来很简单,但我仍然得到相同的错误。我尝试过:

include <iostream>
include <string>    

using namespace std;

int main()
{
  string myString = "";
  cin >> myString;
  long myLong = atol(myString);
}

但总是出现错误:

.../main.cpp:12: error: cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'long int atol(const char*)'

发生了。参考资料中如下所述:
long int atol ( const char * str );

有需要帮忙的吗?
4个回答

12

尝试

long myLong = std::stol( myString );

该函数有三个参数。
long stol(const string& str, size_t *idx = 0, int base = 10);

您可以使用第二个参数来确定在字符串中解析数字停止的位置。例如:

std::string s( "123a" );

size_t n;

std::stol( s, &n );

std::cout << n << std::endl;

输出结果为

3

这个函数可能会抛出异常。


8

只需编写代码

long myLong = atol(myString.c_str());

这是C11标准吗? - gumuruh

3

atol() 需要一个 const char* 参数,std::string 无法进行隐式转换为 const char*,因此如果您真的想使用 atol(),必须调用 std::string::c_str() 方法获取原始的类C字符串指针来传递给 atol()

// myString is a std::string
long myLong = atol(myString.c_str());

更好的 C++ 方法是使用 stol()(自 C++11 起可用),而不是依赖像 atol() 这样的 C 函数:
long myLong = std::stol(myString);

1

atol函数的参数是一个C风格字符串,即const char*类型,但是你作为参数传递了一个std::string类型。编译器无法在const char*std::string之间找到任何可行的转换方式,因此会出现错误。你可以使用std::string成员函数std::string::c_str(),该函数返回一个C风格字符串,等同于你的std::string内容。用法:

string str = "314159265";
cout << "C-ctyle string: " << str.c_str() << endl;
cout << "Converted to long: " << atol(str.c_str()) << endl;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接