gpt4 book ai didi

c++ - 从 char 到 const* char 的无效转换,代码有什么问题?

转载 作者:行者123 更新时间:2023-11-28 04:15:51 25 4
gpt4 key购买 nike

我正在尝试编写一个函数,它接受一个 int 参数并返回它的数字之和。例如,digital_root(123) 将返回 1+2+3,即 6。在 for 循环中我不能将单个字符转换为整数..

应该包括我同时使用了 atoi() 和 stoi() 函数。代码有什么问题?

int digital_root(int x)
{
int t = 0;
string str = to_string(x);
for(char& c : str){
t += atoi(c);
}
return t;
}

我希望字符能成功转换为整数。我该怎么做?

最佳答案

看看std::atoi ,它的参数是 const char* 类型,但您传递的是单个 char。不可能从 char 转换为 const char*,这就是编译器所提示的。

您想要的是通过一些 ASCII 数学运算将 char 转换为 int:

t += static_cast<int>(c)  - '0';

但请注意,虽然这可行,但对于此任务还有更好的解决方案。它不需要转换为字符串,而是完全依赖整数除法,重复使用 % 10

关于c++ - 从 char 到 const* char 的无效转换,代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56683766/

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