c++ - 如何将字符串转换为 ASCII 值的总和?

标签 c++ string ascii

我是初学者,正在学习 CSC 类(class),我必须编写一个程序,将用户输入的字符串转换为每个字符的 ASCII 值之和,这是我目前所拥有的,但我离正在做。但任何帮助将不胜感激。谢谢

#include <iostream>
#include <iostream>
#include <string>
#include <cstring>

using namespace std;
using std::string;
using std::cout;
using std::endl;

int main()
{
    {
        int x;

        std::cout << "enter string" << std::endl;
        std::cin >> x;
    }
    string text = "STRING";

    for (int i = 0; i < text.size(); i++)
        cout << (int)text[i] << endl;

    return 0;
}

最佳答案

您可以使用基于范围的 for 循环来遍历字符串,然后将每个 char 相加:

#include <iostream>
#include <string>

int main()
{
    int sum = 0; // this is where all the values are being added to
    std::string s;
    std::cout << "enter string and press enter." << std::endl;
    std::cin >> s; // string that the user enters will be stored in s

    for (char c : s)
        sum += c;
    std::cout << "total ASCII values: " << sum << std::endl;
    return 0;
}

关于c++ - 如何将字符串转换为 ASCII 值的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55420628/

相关文章:

C++:线程间共享的静态函数成员,可以全部阻塞吗?

java - 使用 While 循环将键盘上的用户输入与字符串进行比较

java - 生成用于暴力破解的 key

java - UTF 到 ASCII 的转换

c++ - 奇怪的段错误

c++ - 找出多态对象的大小

php - 使用_GET的PHP变量语法

检查数组是否为 ASCII

c++ - 在 C++ 中声明纯虚函数时, "= 0;"做了什么?

c# - 在字符串比较中忽略重音字母