如何将字符串转换为 ASCII 值的总和



我是初学者,正在参加CSC课程,我必须编写一个程序,将用户输入字符串转换为每个字符的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;
}

最新更新