variable in a while loop

I would like to have the user type in a word and each letter corresponds to a number, then when the user is finished add up the total. If the the user types in abc the final output would be 6. If use the program below and type in numbers everything works fine, but for the letters the final is always 0. When it enters the loop and the user type in a, the temp variable needs to be 1, but it is staying at 0. Not sure how to get temp to equal the number value of the letter the user inputs.

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
#include <iostream>
using namespace std;
int main ()
{
                int a = 1;
                int b = 2;
                int c = 3;
                int temp;
                int final;
                int counter;
                counter = 1;
                int num;

                cout << " How many letters is your word " << endl;
                cin >> num;
                cout << "Type in your word " << endl;

                while (counter <= num)
                {
                        cin >> temp;
                        final = final + temp;
                  counter++;
                }
cout << final << endl;
return 0;
}

~          
1. store the input of user in a char array , or string object.
2. iterate through the input and check every letter if letter=='a' add value 1 to sum.
Making many if's is not the way to go.
It's really slow and will take a lot of time to write.
1
2
3
4
5
6
char myletter = 'a';
int score=0;
if(myletter >= 'a'  && myletter <= 'z')
    score = int(myletter-'a');
else if(myletter >= 'A' && myletter <= 'Z')
    score = int(myletter-'A');


Or, as an almost one-liner:
1
2
char myletter = 'a';
int score=(myletter>='a'&&myletter<='z')?(myletter-'a'):((myletter>='A'&&myletter<='Z')?(myletter-'A'):0);
Last edited on
I thought this website shouldn't give the full code , but more hints (that's what I did, of course that's slower).
Also don't forget to add a little bit to your code , so that inputing "a" , 1 will be received.
Thanks for the input. I needed to use an int array since I want the letters to be variables for numbers, but I got that working. I need to get a loop and a few other things working, but suggesting the array gave me the right direction.

Topic archived. No new replies allowed.