how do I add this together?

I have a loop which outputs the ASCII values but how do I write another loop which adds those values together?


string name;
int a;
cout<<"Enter string : ";
cin>>name;

for(a = 0; a!=name.length(); ++a)
cout<<int(name[a])<<", ";


If I input cat it shows the values 99, 97 116
I want to have the sum of these outputted out instead of those individual values

Thanks


1
2
3
4
5
6
7
8
9
10
11
12
string name; 
int a;
int sum = 0; 
cout<<"Enter string : "; 
cin>>name;

for(a = 0; a!=name.length(); ++a)
{ 
    sum += int(name[a]);
}

cout << sum;
thanks!
I just realised this only works for one word.
how would I make so it would show the value of two words

eg happy dog

thanks
instead of cin>>name use getline(cin,name) so you can get an entire line or get two strings and sum them together
1
2
3
4
5
6
7
8
9
10
11
12
string name; 
int a;
int sum = 0; 
cout<<"Enter string : "; 
getline(cin,name);

for(a = 0; a!=name.length(); ++a)
{ 
    sum += int(name[a]);
}

cout << sum;


so like that?
Last edited on
yes
i get 0 for the ASCII value output
What input did you give? If you hit enter before entering anything, you'll get an empty string
I put this in so I could put in an input

1
2
    getline(cin,name);
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

You don't need to use ignore() when using std::getline().
I need to for some reason...

that loop there is like just one part. I got other parts to the program.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
   char gender;
   string name;
   
    cout<<"Please enter gender (m/f): ";       //gender selection done as a simple if else statement.
    cin>> gender;
    cout<<endl;
         if (gender == 'm')             // m = male
              cout<< "Sir, what is you name? " <<flush;
         else //f = female output
              cout<< "Madam, what is you name? " <<flush;

    getline(cin, name);
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    cout<<endl;
    cout<< "Your name adds up to " ;
   
    int sum = 0; 
    for(a = 0; a!= name.length( ); ++a)
    { 
      sum += int(name[a]);
    }
    cout<<sum;


this is the program Ive written. If I input just 'm' for the gender and then input a name the sum outputs 0
if I input 'male' then it outputs and then I input a name it outputs a value but its not the correct ascii value.
That is because of your extra characters. you should move cin.ignore before getline or call cin.sync (before getline)
sorry whats "cin.sync"?
I havent learn that yet.
It removes the characters you didn't read from the stream buffer

http://www.cplusplus.com/reference/iostream/istream/sync/
ahhhh okay thank you
Topic archived. No new replies allowed.