从字符到康斯特* 字符的转换无效,代码有什么问题?
Invalid conversion from char to const* char, What is wrong with the code?
>我正在尝试编写一个函数,该函数接受一个整数参数并返回其数字的总和。例如,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
.
相关文章:
- 我的字符计数代码计算错误.为什么
- 有没有办法通过使用十进制 ASCII 代码自动类型扣除来获取字符?
- 使用常量字符*时退出代码 139
- 如何从代码本身向 wxwidgets 中的文本控件插入字符?
- 为什么我的代码在尝试复制字符数组时引发 C6386 错误?
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符
- 使用指针编译代码后,.cpp文件将变为随机字符
- 用最少的代码行数替换c++中的一组字符
- 为什么要更改这两个代码的输出"&"字符?
- C++代码,用于在用户插入的字符串的每个元音之后插入一对字符
- 将代码从 EEPROM 写入字符数组
- 为什么此文件中的字符在C++ (VS2017) 中读入为负字符代码?
- tiny-utf8:以字符/代码点为单位获取偏移量
- 1857 是 A 的另一个字符代码
- 唯一的字符代码在 Linux 中运行时不起作用,但在 Windows (C++) 中很好
- 从ASCII到Unicode字符代码的转换(FreeType2)
- C++ 和 C# 之间的字符代码不同
- 从char中获取字符代码
- 在向富文本框写入数据时获取字符代码而不是字母text属性
- 如何从char*打印字符代码