How to toupper char array in c?

juliandik picture juliandik · Mar 3, 2016 · Viewed 16.6k times · Source

whats wrong here?

I want to check if the char in char array islower, so if it is it should be changed in uppercase.

#include <stdio.h>

int main(int argc, char *argv[]) {
    char arr[100];
    scanf("%s",&arr);
    for(int i=0;i<sizeof(arr);i++){
        if(int islower(arr[i])){
            arr[i] = toupper(arr[i]);
        }
    }
    printf("%s",arr);
    return 0;
}

Answer

abelenky picture abelenky · Mar 3, 2016

To measure the length of a string properly, use strlen, not sizeof

for(int i=0;i<strlen(arr);i++){ // Don't use sizeof on this line

Here's a simpler version:

#include <stdio.h>
#include <ctype.h>

int main(int argc, char *argv[]) {
    char arr[100];
    scanf("%s", arr);

    for(int i=0;i<strlen(arr);i++){
        arr[i] = toupper(arr[i]);
    }

    printf("%s",arr);
    return 0;
}

Or even:

#include <stdio.h>
#include <ctype.h>

int main(void) {
    char arr[100];
    scanf("%s", arr);

    for(char* c=arr; *c=toupper(*c); ++c) ;

    printf("%s",arr);
    return 0;
}