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

Asked

Viewed 7,278 times

6

I’m creating a variable:

char nome[20];

After this, I am 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 I need to do this, using the function toupper() in case the user type the lowercase name, make it uppercase, therefore working the if.

Attempt at the if with toupper:

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

Mistakes :

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

Too Many Arguments to Function 'int toupper(int)'

cannot 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 the if? Or inside it ?

  • 2

    Put the code that you tried so we can see where the error is. And tell us what the errors are.

1 answer

6


The syntax of toupper() it’s not that so it won’t work anyway. EM programming can’t play anything in the code and see if it works. You have to read documentation and see how you have to use it.

Even if the syntax was right it still wouldn’t solve because the documentation says it modifies a character and not all the string.

Converting all characters to then compare them is inefficient. So either you have to do a function that sweeps the whole string comparing without considering the case sensitivity or using a ready-made function. The problem is that it does not have a standard ready function for this. In 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");
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • 2

    Thanks again bigown for the patience for explaining the code, I’m novice compared to everyone here at Stackoverflow, I program only 2 years, and I’m not used to looking at the C documentation (other languages I always look at), but I’ll start looking yes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.