c++ - 添加该行的所有总和

标签 c++ string c++17

我想在 get_line_sum 函数中获取字符串中每个字符的总和(例如:“1300321”将返回 10)。但是,我的总和似乎与我想得到的不匹配。

#include <iostream>
#include <string>
int get_line_sum(std::string x) {
    int total = 0;
    for (char &c : x) total += c;
    return total;
}
int main() {
    std::cout << get_line_sum("1300321") << std::endl;
}
c:    1   total:   0
c:    3   total:   49
c:    0   total:   100
c:    0   total:   148
c:    3   total:   196
c:    2   total:   247
c:    1   total:   297
346

输出是 346,而不是 10。我打印了每个字符和总数,以便更容易看到发生了什么。

最佳答案

您是在对字符代码求和,而不是对文字数字求和。 See the ASCII table .

ASCII 码:

  • '1' 是 49
  • '3' 是 51
  • '0' 是 48
  • '2' 是 50

因此你得到 49 + 51 + 48 + 48 + 51 + 50 + 49 即 346。

关于c++ - 添加该行的所有总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58245078/

相关文章:

javascript - 用于匹配字符串开头和结尾的两个单引号的正则表达式

c++ - operator-> 用于返回临时值的迭代器

c++ - 如何在 C++ 中运行剪辑?

c++ - 是什么导致 Visual Studio 调试器使某些问题无法重现?

c++ - Visual Studio 的编译器在哪里搜索#includes?

python - C++ 17 与 Python 2.7 的兼容性

c++ - 使用 std::tuple_cat 模板实例化 decltype 和 declval

c++ - CGAL新手问题: Which segments intersect?

excel - 用字符串变量替换字符串 - 错误 91

java - 将 inputStream 从 ZipFile 转换为 String