1

I am writing a C++ console application and I'm turning a into 1, b into 2 and so on. Thing is, it's outputting numbers like 48 and 52 - even though the array I'm basing it off only goes up to 26.

Here's the code:

void calculateOutput() {

    while (input[checkedNum] != alphabet[checkedAlpha]) {
        checkedAlpha++;
        if (checkedAlpha > 27) {
            checkedAlpha = 0;
        }
    }

    if (input[checkedNum] == alphabet[checkedAlpha]) {
        cout << numbers[checkedAlpha] << "-";
        checkedAlpha = 0;
        checkedNum++;
        calculateOutput();
    }
}

Here is my number and alphabet arrays:

char alphabet [27] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','o','p','q','r','s','t','u','v','w','x','y','z',' '};

int numbers [27] = { '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','0' };
5
  • 2
    How are input, alphabet, and numbers defined? Commented Aug 22, 2017 at 5:37
  • 2
    Hint: inputAlphabet - 'a' + 1 would give what you need Commented Aug 22, 2017 at 5:38
  • Where does the numbers array come from? Regardless, your output (stuff like 48 and so on) sounds like ASCII values. Commented Aug 22, 2017 at 5:40
  • 1
    @plezhelpmeh please edit the question with the added data... Commented Aug 22, 2017 at 5:42
  • Offish topic: en.wikipedia.org/wiki/EBCDIC Commented Aug 22, 2017 at 5:51

2 Answers 2

3

Its int array so it means that it will save ASCII values of characters.

If you would look carefully on ASCII table, you would find out that 48,49,50,... are ascii values of numbers 0,1,2,...

What you have to do is deduct value of first number in table -> '0' (48)

cout << numbers[checkedAlpha] - '0' << "-";

or better, save numbers as numbers not characters

 int numbers [27] = { 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​,0 };

Btw. here is hint which make it easier for you

tolower(inputAlphabet[index]) - 'a' + 1  // For 'a' output is 1 and so on :-)
Sign up to request clarification or add additional context in comments.

1 Comment

I'm glad it helped you, remember that ascii table. :-)
0

The algorithm to get the number (i9ndex) of the letters of the alphabet is quite simple. No need for tables, a simple subtraction does the trick.

int getLetterIndex(char c)
{
    // returns -1 if c is not a letter
    if ('a' <= c && c <= 'z')
        return 1 + c - 'a';
    if ('A' <= c && c <= 'Z')
        return 1 + c - 'A';
    return -1; 
} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.