C++ toUpper Implementation

Davlog picture Davlog · Jun 3, 2013 · Viewed 8.1k times · Source

I made an implementation of toUpper(). It doesn't work 100%.

Code :

char* toUpper(char* string)
{
    char* sv = string;
    while(*sv++ != '\0')
    {
        if( int(*sv) >= 97 || int(*sv) <= 122)  //Only if it's a lower letter
            *sv = char( *sv - 32);
    }
    return string;
}

I know that the lower letters have the numbers from 97 to 122 (in ASCII) and the upper letters have the numbers from 65 to 90. There are exactly 32 numbers between the lower to the upper letter. So I just subtracted 32 from the lower character.

Code where I call this function :

char h[] = "Whats up?";
cout << toUpper(h) << endl;

I expected the program to output "WHATS UP?" but instead I got "WHATS". What did I do wrong?

Answer

simonc picture simonc · Jun 3, 2013
if( int(*sv) >= 97 || int(*sv) <= 122)

should be

if( int(*sv) >= 97 && int(*sv) <= 122)

or, preferably

if( *sv >= 'a' && *sv <= 'z')
    *sv = *sv - ('a' - 'A');

You also need to move the point at which you increment sv. The current code skips checking the first character in string

while(*sv != '\0')
{
    if( *sv >= 'a' && *sv <= 'z')
        *sv = *sv - ('a' - 'A');
    sv++;
}

Lastly, I'm sure you're aware of it but just in case... if this isn't a homework assignment or other learning exercise, the standard C toupper function will do exactly the same job for you

*sv = (char)toupper(*sv);