Comparing char variable in C

Asked

Viewed 71 times

0

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

int main() {

    struct cmd1 {

        char cmd[20];

    };

    struct cmd1 cmdd;

    char cmd_ti[3] = "ti";
    char cmd_tela1[2] = "a";

    printf("\nTeste -> ");
    fgets(cmdd.cmd, 20, stdin); //O que foi digitado pelo usuario
    __fpurge(stdin);


    printf("\nDigitado pelo usuario: %s", cmdd.cmd); //teste pra ver o que ta imprimindo
    printf("\ncmd_ti:  %s", cmd_ti); //teste pra ver o que ta imprimindo
    printf("\ncmd_t1:  %s", cmd_tela1); //teste pra ver o que ta imprimindo

    if (strcmp(cmd_ti, cmdd.cmd) == 0) {

        printf("\nOK");
        printf("\n%s == %s", cmd_ti, cmdd.cmd);

    } else {

        printf("\nNOT OK");
        printf("\n%s != %s", cmd_ti, cmdd.cmd);

    }


    return(0);
}

I need "you" to equal "you" in comparison. I’ve searched a lot of places, and I still can’t figure out what’s going on. Does anyone know how to help me because when I type you it doesn’t compare to the variable I’ve already left declared as you?

1 answer

1


The value you are reading from stdin contains what the user has typed, including the ENTER. If you change the two lines of else down the lines, you’ll see the problem:

    printf("\nNOT OK");
    printf("\n--%s-- != --%s--", cmd_ti, cmdd.cmd);

To fix this you can remove the spaces from the end of cmdd.cmd (if spaces are significant then you need to remove only CRLF/LF), as in the example below.

void trimEnd(char *str) {
    char *end = str + strlen(str) - 1;
    while (end > str && isspace(*end)) end--;
    end++;
    *end = 0;
}

int main() {

    struct cmd1 {

        char cmd[20];

    };

    struct cmd1 cmdd;

    char cmd_ti[3] = "ti";
    char cmd_tela1[2] = "a";

    printf("\nTeste -> ");
    fgets(cmdd.cmd, 20, stdin); //O que foi digitado pelo usuario
    //__fpurge(stdin);


    printf("\nDigitado pelo usuario: %s", cmdd.cmd); //teste pra ver o que ta imprimindo
    printf("\ncmd_ti:  %s", cmd_ti); //teste pra ver o que ta imprimindo
    printf("\ncmd_t1:  %s", cmd_tela1); //teste pra ver o que ta imprimindo

    if (strcmp(cmd_ti, cmdd.cmd) == 0) {

        printf("\nOK");
        printf("\n%s == %s", cmd_ti, cmdd.cmd);

    } else {

        printf("\nNOT OK");
        printf("\n--%s-- != --%s--\n", cmd_ti, cmdd.cmd);

    }

    trimEnd(cmdd.cmd);
    if (strcmp(cmd_ti, cmdd.cmd) == 0) {

        printf("\nOK");
        printf("\n%s == %s", cmd_ti, cmdd.cmd);

    } else {

        printf("\nNOT OK");
        printf("\n--%s-- != --%s--\n", cmd_ti, cmdd.cmd);

    }

    return(0);
}
  • I understood where the mistake is now, but I still do not understand what I can do to take the enter. You could help me?

  • The above code removes enter - update your browser (F5) and you will see.

  • Ah, I get it. Thank you. ;)

Browser other questions tagged

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