Convert Alphabets To Numbers.

Hi guys, I am a newbie in programming and learning it by myself. I am trying to convert alphabet letters to integer and get the sume from the letters that the user input. My question is, is it safe to use this line of code in my program "numVal = (int)(alpha[w] - 'A' + 1);"

Below is the progress of my program. I am still going to add a condition to check if the user input a space on the words. Also please let me know if there are lines that I can still improve.


TIA

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
  

#include <iostream>
#include <cctype>


int main(){


	std::string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	std::string text = " ";
	int numVal = 0;
	int sum = 0;

	std::cout << "Enter text: ";
	std::cin >> text;


	for(unsigned int i = 0; i < text.size(); i++){ //Check if letters are lower case then convert it to upper case.
		if(islower(text[i])){
			text[i] = toupper(text[i]);
		}
	}

	for(unsigned int y = 0; y < text.size(); y++){
		for(unsigned int w = 0; w < alpha.size(); w++){ //Do the conversion from letters to int.
			if(text[y] == alpha[w]){
				numVal = (int)(alpha[w] - 'A' + 1);
				sum += numVal;
			}
		}
	}

	std::cout << sum;

	return 0;
}
Last edited on
prefer static_cast over the c-style casts:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <cctype>
#include <string>

int main()
{
    std::cout << "Enter text \n";
    std::string text{};
    getline(std::cin, text);
    int sum{};
    for (auto& elem : text)
    {
        if(isalpha(elem))
        {
            elem = toupper(elem);
            sum += static_cast<int>(elem - 'A' + 1);
        }
    }
    std::cout << sum << "\n";
}
The result of the expression the expression alpha[w] - 'A' or elem - 'A' depends on the locale-specific character encoding in use by the implementation.
For instance, 'B' - 'A' need not be equal to 1; it could even be negative.

This would be correct and robust:
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
#include <iostream>
#include <string>
#include <cctype>

int main()
{
    const std::string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    std::string text ;
    std::cin >> text ;

    // convert all lower case characters to upper case
    for( char& c : text ) c = std::toupper(c) ;

    // sum up the values of alpha characters ('A' == 1, 'B' == 2 etc.)
    int sum = 0 ;
    for( char& c : text ) // for each character c in text
    {
        // locate the character in alpha
        // http://www.cplusplus.com/reference/string/string/find/
        const auto pos = alpha.find(c) ;

        if( pos != std::string::npos ) // if found (if the character is an alpha character)
                                       // note: non-alpha characters are ignored
        {
            const int value = pos + 1 ; // +1 because position of 'A' is 0, value of 'A' is 1
            sum += value ;
        }
    }
}
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
#include<iostream>
#include<string>
#include<cctype>
#include<map>
using namespace std;

main()
{
   const string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   map<char,int> myMap;

   for ( int i = 1; i <= 26; i++ )
   {
      myMap[          alpha[i-1]   ] = i;
      myMap[ tolower( alpha[i-1] ) ] = i;
   }

   string text;
   cout << "Enter text: ";
   getline( cin, text );

   int sum = 0;
   for ( char c : text ) if ( myMap.count( c ) ) sum += myMap[c];
   cout << "Sum is " << sum;
}


Enter text: Hello, world!
Sum is 124
Thanks for the response guys.

Hi guys, sorry for the follow up question, I just want to know, can someone explane what this code does?

(alpha[w] - 'A' + 1)

I just this one on the internet but it didn't have any explanation as to what it does in the background.
Hi skawt05,

Each character in the collating sequence is actually stored as a sort of integer (which may differ between implementations). If you try
int i = 'A';
you will be able to find out which one actually stores 'A' on your machine, for example.

In the ASCII character set (and many/most others - but not all: see below) these characters are in successive sequence. So 'B' is 1 more than 'A', 'C' is 2 more than 'A', 'D' is 3 more than 'A'. Thus, if you did
'B' - 'A'
in such a sequence you would get 1. Similarly,
'C' - 'A'
would produce 2 ... and so on. If you want to get 1, 2, 3 ... for 'A', 'B', 'C' then you will have to correct by adding 1. Thus IF your character series is in successive order then
(alpha[w] - 'A' + 1)
would number the upper case letters from 1 to 26. Note that the lower-case letters, however, are quite a long way from the upper-case ones.

The problem, as @JLBorges pointed out right at the start, is that you can't guarantee that the characters are in successive order like this - it may depend on your locale or the machine's collating sequence. If you want a notorious example see
https://en.wikipedia.org/wiki/EBCDIC#Criticism_and_humor
and note that this was devised by IBM!

So the answer is ... on most English/American PCs this code will map the upper case alphabet to the numbers 1-26 ... it's just that you can't rely on that fact.

The later codes in this thread try to map the alphabet directly to numbers (taking into account case on the way) and lessen the portability issues.
Last edited on

Thanks lastchance, it makes sense now.
Topic archived. No new replies allowed.