将字符串转换为长字符串

新手上路,请多包涵

我正在尝试将字符串转换为长字符串。这听起来很容易,但我仍然遇到同样的错误。我试过了:

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

有什么帮助吗?

原文由 PEAR 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 668
1 个回答

尝试

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

该函数可以抛出异常。

原文由 Vlad from Moscow 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题