我是初学者,正在学习 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/