Summing the characters in a word or sentence

I would like to be able to type a string and get the ascii value back of the every character and return a total of the word or sentence. for example if you were to type in beans

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <string>

using std::string;
using std::cout;
using std::cin;
using std::endl;
int main(){

string sentence;
int sum = 0;


/*
if user entered beans
my goal would be to add 98+101+97+110+115
*/

cout<<" What do you want to say? \n";
getline(cin,sentence);

for(int i=0; i<sentence.length();i++)
{
char c = sentence[i];
int ac = int(c);

//I thought this would work? should I use a while loop?

sum =+int(c);
cout<< c<<" "<<"  "<<ac<< " "<<sum<<endl;


}//end for 
cout<<sentence<<" \n";

}//end main

Last edited on
cout<<static_cast<int>(sentence[i]);
That is not how to convert a char into the int value it represents.
http://www.cplusplus.com/forum/beginner/68260/

sum and num begin as random values. This is a bad thing.

that said, what is num meant to represent? Your code doesn't make any sense. What are you trying to do? If the user enters the word "beans", what output are you trying to get?

I would like to make a function that took the characters of the word or words that I type and add them up and return the sum. I was attempting to prototype this here, but I got stuck as the += operator seems to just display the ascii value again, where I would like to see it add it to the last character that was iterated.
You inverted the order of the addition assignment operator.
+= and =+ are actually two very different things.
The first one is the addition assignment operator and carries out two function: it takes its left operand, sums it to the right operand, and assigns the result to the left operand.
The second one isn't a single operator, but two: the assignment operator = which takes the expression you give it as your left operand and the unary plus operator, which multiplies the right hand operand times 1.
In your code, you assign the value of the latest character to sum instead of progressively adding values up to it, so you get a wrong value when the for ends.
Also, i think you meant to do cout << sum << "\n"; in the last line.
Topic archived. No new replies allowed.