how do I add this together?
takumi05 (18)
Apr 20, 2009 at 9:29am UTC
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
yang (33)
Apr 20, 2009 at 9:50am UTC
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;
takumi05 (18)
Apr 20, 2009 at 10:09am UTC
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
Bazzy (6258)
Apr 20, 2009 at 11:37am UTC
instead of cin>>name use getline(cin,name) so you can get an entire line or get two strings and sum them together
takumi05 (18)
Apr 20, 2009 at 12:36pm UTC
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 Apr 20, 2009 at 12:37pm UTC
takumi05 (18)
Apr 20, 2009 at 12:39pm UTC
i get 0 for the ASCII value output
Bazzy (6258)
Apr 20, 2009 at 12:46pm UTC
What input did you give? If you hit enter before entering anything, you'll get an empty string
takumi05 (18)
Apr 20, 2009 at 12:48pm UTC
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' );
helios (9408)
Apr 20, 2009 at 2:22pm UTC
You don't need to use ignore() when using std::getline().
takumi05 (18)
Apr 21, 2009 at 2:59am UTC
I need to for some reason...
that loop there is like just one part. I got other parts to the program.
takumi05 (18)
Apr 21, 2009 at 10:38am UTC
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.
Bazzy (6258)
Apr 21, 2009 at 11:45am UTC
That is because of your extra characters. you should move cin.ignore before getline or call cin.sync (before getline)
takumi05 (18)
Apr 21, 2009 at 12:38pm UTC
sorry whats "cin.sync"?
I havent learn that yet.
Topic archived. No new replies allowed.