Reputation: 31
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' };
Upvotes: 1
Views: 106
Reputation: 6467
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 :-)
Upvotes: 3
Reputation: 6461
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;
}
Upvotes: 0