【问题标题】:How to convert a string into the sum of ASCII values?如何将字符串转换为 ASCII 值的总和?
【发布时间】:2023-03-29 14:32:01
【问题描述】:

我是一个初学者,正在学习 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;
}

【问题讨论】:

  • 你有什么问题?
  • 大概,ASCII 在这里用作genericized trademark(如 Kleenex 或 Xerox)。通用术语是“字符代码”。字符编码可能因系统、终端、用户和时间而异,而且几乎可以肯定不是 ASCII。对于相同的输入字符串,不同的字符编码可能有不同的字符代码。

标签: c++ string ascii


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2012-01-17
    • 2013-09-27
    • 1970-01-01
    相关资源
    最近更新 更多