How do I take a string of characters and sum their ascii values?

Could someone please explain to me how would I take a string of characters such as 'ABCDEFGHI' and convert them to their ascii values so I can sum them?

You can do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int stringASCIISum(const string& stringLetters)// const means you cannot change your referenced string object
//You want to do this if you don't intend your string variable from being changed inside this function.
//For this little program, you don't really need the const but this is good to know.
//Ampersand(&) after type denotes a referenced object or type. This means the passed outside object can be changed from inside this function. 
//But not if you make it const.
{
    int ASCII;
    int sum = 0;
    for( int i = 0; i < stringLetters.size(); i++) //stringLetters is your string variable.
    {
        ASCII = stringLetters[i]; //ASCII stores the int value of stringLetters[i].

        sum += ASCII; // sum = sum + ASCII
    }
    return sum;
}
Last edited on
in the code you provided can you explain what the str[i] is?
str[i] is an array of characters. A string, in other words. Basically what the loop is doing, is it's going through from the first to last character of any given word (or ascii character in your case), and getting the integer value it is assigned.
Yea I made a mistake. I initially called the string "str", but then changed it to stringLetters and forgot to change str to stringLetters on line 9. I also added const to the referenced string parameter and a brief explanation.
Last edited on
Since a character is an integral type, you can just use accumulate which is in <numeric>:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <numeric>
#include <string>

int main()
{
	std::string test = "ABCDE";
	int sum = std::accumulate( test.begin(), test.end(), 0 );
	std::cout << sum;
	
	return 0;
}


See accumulate: http://www.cplusplus.com/reference/numeric/accumulate/
Topic archived. No new replies allowed.