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

时间:2019-03-29 15:22:25

标签: c++

我是一名初学者,正在学习CSC课程,我必须编写一个程序,将用户输入的字符串转换为每个字符的ASCII值的总和,这是我到目前为止所要做的,而Im距离还很远正在完成。但任何帮助将不胜感激。谢谢

#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;
}

1 个答案:

答案 0 :(得分:1)

您可以使用基于范围的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;
}