简体   繁体   中英

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?

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);

Having ++ in the while makes you miss important cases. The int() things are unnecessary noise. You need && in the check condition. The action can be written with -=.

Here's a rewrite that uses a for loop and fixes your conditional as well as off-by-one increment:

char* toUpper(char* string)
{
    for(char* p=string; *p != '\0'; p++)
    {
        if(*p >= 'a' && *p <= 'z')  //Only if it's a lower letter
          *p -= 32;
    }
    return string;
}

re: "I expected the program to output "WHATS UP?" but instead I got "WHATS". What did I do wrong?" You didn't supply the code that is defective. If I had to guess, in main you are calling argv[1], But I am only guessing as your main is not included.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM