How to use the toupper () function in char in C?

5

I'm creating a variable:

char nome[20];

After this, I'm asking the user to enter a name:

printf("Digite um nome : ");
scanf("%20s",&nome);    

And I'm checking to see if the name is correct:

if(strcmp(nome,"Maria") == 0){
    printf("\nCor favorita : Vermelho");
    printf("\nFruta favorita : Morango");
}

The problem is that I need to do this, using the toupper() function in case the user type the lowercase name, it causes it to be uppercase, so running if .

Attempting if with toupper :

if(strcmp(toupper(nome,"maria")== 0)){
        printf("\nCor favorita : Vermelho");
        printf("\nFruta favorita : Morango");
    }

Errors:

  

invalid conversion from 'char *' to 'int' [-fpermissive]

     

too many arguments to function 'int toupper (int)'

     

can not convert 'bool' to 'const char *' for argument '1' to 'int strcmp (const char *, const char *)'

I would have to convert the variable with the function toupper() before if ? Or inside it?

    
asked by anonymous 28.03.2017 / 20:06

1 answer

5

The syntax of toupper() is not this so it will not work at all. In programming you can not play anything in the code and see if it works. You have to read documentation and see how you have to use it.

Even though the syntax was right, it still would not resolve because the documentation says that it modifies a character and not the whole string.

Converting all characters to then comparing them is inefficient. So either you have to do a function that scans the entire string by comparing it without considering the box sensitivity or using a ready function. The problem is that it does not have a standard ready function for this. On Windows there is a _stricmp() ". On Linux you can use strcasecmp() .

#include <stdio.h>
#include <string.h>
#include <strings.h>

int main(void) {
    char lugar[20]; //cria o array de caracteres para armazenar o texto
    printf("Digite o nome de um lugar: ");
    scanf("%20s", lugar); //não precisa da referência porque o array já é uma, precisa %s
    if (strcasecmp(lugar, "Escola") == 0) { //use a função para comparar todos os caracteres
        printf("\nEstudar");
    }
}

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

    
28.03.2017 / 20:25