Home > database >  Can't display the entire string when translating CHAR to INT
Can't display the entire string when translating CHAR to INT

Time:11-27

In my intro class, I'm tasked with translating a phone number that may have letters in it, back to a pre-determined list of numbers (like 1-800-COLLECT would display as 1-800-2655328) and currently, I can translate the letters to numbers but for whatever reason, the non-letters in the phone numbers arent being translated. This is the main function:

int main()
{
    string original;
    cout << "Please enter a phone number with letters: ";
    getline(cin, original);
    cout << "This is your number without letters: ";
        for (int i = 0; i < original.length(); i  )
        {
            if (original[i] < 0 || original[i] > 9)
            {
                translate(original[i]);
            }
            else
                cout << original[i];
        }
}

The translate function simply takes whatever element its fed and, if it falls between Aa - Zz it will display a predetermined number. (Aa - Cc would display the number 2, etc) So far it works for translating, as when I put in "1800GOTJUNK" it returns "4685865" fine, but won't acknowledge the "1800" before it, I think there's something wrong with how I'm structuring the if and for statements to display everything correctly, can someone give me some advice?

CodePudding user response:

This:

if (original[i] < 0 || original[i] > 9)

Is comparing against the ASCII codes 0 and 9, not the actual characters. It should be:

if (original[i] < '0' || original[i] > '9')
  •  Tags:  
  • c
  • Related