Search code examples
ccapitalization

Simple capitalization of first letter of each word in C


I want to capitalize first letter of each word of an entered string.

This is what I've done (doesn't work yet)

void main() {
     char sentence[100];
     int i;

     printf("Enter your name and surnames: ");
     gets(sentence);

     for(i = 0; i<strlen(sentence); i++){
        if(sentence[i] == ' '){
            printf("%c", toupper(sentence[i]+1)); 
            //I want to advance to next item respect to space and capitalize it
            //But it doesn't work
        } else {
            printf("%c", sentence[i]);
        }
     }
} 

Input: james cameron

Wished Output: James Cameron


Solution

  • So close.

    printf("%c", toupper(sentence[i]+1)); 
    

    Should be

    printf(" %c", toupper(sentence[i+1]));
    i++;
    

    Though you should probably check for the end of the string ('\0') too.