从字符到康斯特* 字符的转换无效,代码有什么问题?

Invalid conversion from char to const* char, What is wrong with the code?

本文关键字:字符 代码 什么 问题 转换 康斯特 无效      更新时间:2023-10-16

>我正在尝试编写一个函数,该函数接受一个整数参数并返回其数字的总和。例如,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.