Search code examples
cwhile-loopcharc-stringstoupper

How to use toupper on char * in C?


So I have a problem with using toupper on char *. Let me show you what I tried.

#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
    char* shi = command->args[0]; //which is "binance"

    while(*shi) {
        toupper((unsigned char) *shi);
        shi++;
    
    }

    printf("Capitalized version is: %s",shi); // which should be "BINANCE".

return 0;
}

Solution

  • This statement

    toupper((unsigned char) *shi);
    

    has no effect. The result of the call of toupper is not used.

    Also after this while loop

    while(*shi) {
        toupper((unsigned char) *shi);
        shi++;
    
    }
    

    the pointer shi points to the terminating character '\0' of the string.. So the following call of printf

    printf("Capitalized version is: %s",shi);
    

    will deal with an empty string.

    You should write for example

    for ( char *p = shi; *p; ++p ) {
        *p = toupper((unsigned char) *p);
    }