gpt4 book ai didi

c++ - 将字符串转换为长

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:04:13 25 4
gpt4 key购买 nike

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

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

有什么帮助吗?

最佳答案

尝试

long myLong = std::stol( myString );

函数有3个参数

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

函数可以抛出异常。

关于c++ - 将字符串转换为长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22733088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com