Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading