C++ 程序查找字符串中 ASCII 值之和

在 C++ 中,每个字符都有一个内部 ASCII 值。在此 C++ 程序中,我们查找给定字符串中 ASCII 值之和。在此 C++ 代码中,我们使用 for 循环 (for(int i = 0; i < txt.size(); i++)) 来迭代从 0 到字符串长度的值。在其中,我们将字符串中每个字符的 ASCII 值添加到 txtASCII_Sum (txtASCII_Sum = txtASCII_Sum + txt[I];) 中。此处,cout << “\nThe ASCII Value of “<< txt[i] << ” = ” << (int)txt[i]; 语句会打印每个字符串字符的 ASCII 值。

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
	int txtASCII_Sum = 0;
	string txt;
	
	cout << "Please Enter any String you want  =  ";
	getline(cin, txt);
	
	for(int i = 0; i < txt.size(); i++)
	{
		cout << "\nThe ASCII Value of "<< txt[i] << " = " << (int)txt[i];
		txtASCII_Sum = txtASCII_Sum + txt[i];
	}
	
	cout << "\n\nThe Sum of ASCII Value in "<< txt << " String = " << txtASCII_Sum;
		
 	return 0;
}
C++ Program to find Sum of ASCII values in a String

C++ 程序使用 While 循环查找字符串中 ASCII 值之和

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
	int i = 0, txtASCII_Sum = 0;
	string txt;
	
	cout << "Please Enter any String you want  =  ";
	getline(cin, txt);
	
	while(i < txt.length())
	{
		cout << "\nThe ASCII Value of "<< txt[i] << " = " << (int)txt[i];
		txtASCII_Sum = txtASCII_Sum + txt[i];
		i++;
	}
	
	cout << "\n\nThe Sum of ASCII Value in "<< txt << " String = " << txtASCII_Sum;
		
 	return 0;
}
Please Enter any String you want  =  tutorial gateway

The ASCII Value of t = 116
The ASCII Value of u = 117
The ASCII Value of t = 116
The ASCII Value of o = 111
The ASCII Value of r = 114
The ASCII Value of i = 105
The ASCII Value of a = 97
The ASCII Value of l = 108
The ASCII Value of   = 32
The ASCII Value of g = 103
The ASCII Value of a = 97
The ASCII Value of t = 116
The ASCII Value of e = 101
The ASCII Value of w = 119
The ASCII Value of a = 97
The ASCII Value of y = 121

The Sum of ASCII Value in tutorial gateway String = 1670

使用 For 循环和函数查找字符串中 ASCII 值之和的 C++ 程序。

#include<iostream>
#include<string.h>
using namespace std;

int sumOfASCIIValuesinaString(string txt)
{
	int txtASCII_Sum = 0;
	
	for(int i = 0; i < txt.size(); i++)
	{
		cout << "\nThe ASCII Value of "<< txt[i] << " = " << (int)txt[i];
		txtASCII_Sum = txtASCII_Sum + txt[i];
	}
	
	return txtASCII_Sum;
}

int main()
{
	int Sum = 0;
	string txt;
	
	cout << "Please Enter any String you want  =  ";
	getline(cin, txt);
	
	Sum = sumOfASCIIValuesinaString(txt);
	
	cout << "\n\nThe Sum of ASCII Value in "<< txt << " String = " << Sum;
		
 	return 0;
}
Please Enter any String you want  =  hello

The ASCII Value of h = 104
The ASCII Value of e = 101
The ASCII Value of l = 108
The ASCII Value of l = 108
The ASCII Value of o = 111

The Sum of ASCII Value in hello String = 532