Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ toUpper Implementation

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?

like image 615
Davlog Avatar asked Jun 03 '26 08:06

Davlog


1 Answers

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);
like image 104
simonc Avatar answered Jun 04 '26 23:06

simonc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!