gpt4 book ai didi

c++ - 将 const 字符串转换为整数数组?

转载 作者:行者123 更新时间:2023-11-28 00:49:43 26 4
gpt4 key购买 nike

您好,我正在尝试将 const 字符串转换为 int 数组,但是当我尝试时它不允许这样做。我的代码是:

int isRegistered(const char str[]) {

int isbnInt[10], i;
//char isbnArray[10];

//isbnArray = str; ----> something I tried

for (i = 0; i < 10; i++)
{
isbnInt[i] = atoi(str[i]);
cout << isbnInt[i] << endl;
}
}

但是当我尝试编译它时,我收到一条错误消息“从 char 到 const char* 的转换无效”

最佳答案

atoi 调用需要一个 const char * 参数,而您传递一个 char,这就是问题所在。

您只需执行以下操作即可将字符转换为数字。这将从字符本身中减去 0 的 ascii 值(因为 0-9 在 ascii 代码中按顺序递增。)

isbnInt[i] = str[i] - '0';

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

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