Comparing char variable in C

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 "ti" to be equal to "ti" in the comparison. I have already researched in several places and still can not understand what is happening. Does anyone know how to help me because when I type ti it does not compare with the variable I already left declared as ti?

    
asked by anonymous 29.10.2015 / 21:53

1 answer

1

The value you are reading from stdin contains what the user entered, including ENTER . If you swap the two lines of else along the lines below, you'll see the problem:

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

To correct this you can remove spaces from the end of cmdd.cmd (if spaces are significant then you need to remove only the 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);
}
    
29.10.2015 / 22:05