Converting Char * to Uppercase in C

EDEDE picture EDEDE · Feb 3, 2016 · Viewed 72.5k times · Source

I'm trying to convert a char * to uppercase in c, but the function toupper() doesn't work here.

I'm trying to get the name of the the value of temp, the name being anything before the colon, in this case it's "Test", and then I want to capitalize the name fully.

void func(char * temp) {
 // where temp is a char * containing the string "Test:Case1"
 char * name;

 name = strtok(temp,":");

 //convert it to uppercase

 name = toupper(name); //error here

}

I'm getting the error that the function toupper expects an int, but receives a char *. Thing is, I have to use char *'s, since that is what the function is taking in, (I can't really use char arrays here, can I?).

Any help would be greatly appreciated.

Answer

chux - Reinstate Monica picture chux - Reinstate Monica · Feb 3, 2016

toupper() converts a single char.

Simply use a loop:

void func(char * temp) {
  char * name;
  name = strtok(temp,":");

  // Convert to upper case
  char *s = name;
  while (*s) {
    *s = toupper((unsigned char) *s);
    s++;
  }

}

Detail: The standard Library function toupper(int) is defined for all unsigned char and EOF. Since char may be signed, convert to unsigned char.

Some OS's support a function call that does this: upstr() and strupr()