How to receive a string and switch to check in C?

Asked

Viewed 1,728 times

5

I have to develop an algorithm that gets the name of a place, for example, "School", and based on this, do a check of the string in the switch, and if it is "School", then it sends a message to the user about what to do, for example, "Study".

Code :

 int main() {

    setlocale(LC_ALL,"portuguese");

    char lugar;

    printf("Digite o nome de um lugar : ");
    scanf("%c",&lugar);

    switch(lugar) {

    case 'Escola' :
    printf("Estudar");
    break;  


    }


 }

Error :

[Warning] Character Constant Too long for its type

[Error] switch Quantity not an integer

From what I’ve seen in C, the concept of string, and ends up being more like a array than string, the concept being vague

  • This is not possible, we can do with if or a much more complex solution (hash for example). Actually the code has other problems, it is even allowing to type the word.

  • So, with if I can do this ? I want to know how, as it is even really allowing you to type the word.

  • 2

    Mondial, did you notice that you are reading only one character? You are not reading a string. Use scanf("%s", lugar) to read a string.

  • Thank you Jefferson for the clarification, I was wrong in some exercises simply because of this mistake, well, I have corrected here and I will remember in the future about this.

2 answers

7


The code has several problems. Need to store the string, need to read with the correct format, need to use if and strcmp() to compare strings.

#include <stdio.h>
#include <string.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 (strcmp(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.

  • Thank you so much for showing the code and for your patience for explaining it. I am new to C and therefore make some silly mistakes myself.

2

In C, you can only put scalar constants in one switch. A string is a pointer type variable, so we will have difficulties using exactly this method.

At Stackoverflow in English, who replied suggested that a function of hash to use the switch with the string; or else use what they called "ladder" if-else.

Wikipedia has a input explaining hash functions. A function of hash for a generic string can be defined like this (I will not do null-safe):

int hash_function(char *str) {
    int acc = 0;
    int peso = 1;
    int base = 256;
    int len = strlen(str);
    int modulus = 65000;

    int i;
    for (i = 0; i < len; i++) {
        int char_at = str[i]; /* char é um número de 8 bits, enquanto que int é um número de 16 ou 32 bits, dependendo do compilador */
        acc = (acc*base + peso*char_at) % modulus;
        peso = (peso % 10) + 1; /* peso varia de 1 a 10 */
    }

    return acc;
}

Having the function of hash predetermined, we already know what can be the value of "School" and creating the macro HASH_ESCOLA:

int tratar_escola(char *lugar) {
    int hash_lugar = hash_function(lugar);
    switch (hash_lugar) {
    case HASH_ESCOLA:
        /* vamos checar se deu positivo verdadeiro? */
        if (strcmp(lugar, "Escola") == 0) {
            printf("Estudar\n");
            return 1;
        }
    }
    return 0;
}

An algorithm of hash/dispersion algorithm can generate collisions (wikipedia article), which in this case is another object that returns the same value as your desired object. To prevent it from colliding with a value other than Escola, i do the comparison with the original string.

Browser other questions tagged

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