Search code examples
cif-statementc-stringsfgetsstrcmp

Comparisons between two strings don't work


I'm writing a menu and I try to choose a option with a string. Following the concerned part my program :

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

int main()
{
    char choix_utilisateur[100];

    printf("Choisissez votre douleur :\n");
    printf("- > Mastermind\n");
    printf("- > Pierre Feuille Ciseaux\n");
    printf("- > Juste Prix\n");
    printf("- > Pendu\n");

    fflush(stdin);
    fgets(choix_utilisateur, 100, stdin);
    printf("%s\n", choix_utilisateur);

    if(!strcmp(choix_utilisateur, "toto")){
        printf("- > Mastermind\n");
    }
    else if(!strcmp(choix_utilisateur, "Pierre Feuille Ciseaux")) {
        printf("- > Pierre Feuille Ciseaux\n");
    }
    else if(!strcmp(choix_utilisateur, "Juste Prix")) {
        printf("- > Juste Prix\n");
    }
    else if(!strcmp(choix_utilisateur, "Pendu")) {
        pendu();
    }
    else {
        printf("Ecris autre chose\n");
    }

    return 0;
}

Here, when I write Pendu, the program select the else without go in the :

else if(!strcmp(choix_utilisateur, "Pendu")) {
        pendu();
    }

With some tests, I saw that strcmp doesn't work as it is expected and return 1 to strcmp(choix_utilisateur, "Pendu") with choix_utilisateur = "Pendu" (I verified, the value variable takes the good value with the fgets). I also try with a char tab[] = "Pendu" and it doesn't work too.

Do you have any idea of the problem ? Thanks by advance.


Solution

  • For starters this call

    fflush(stdin);
    

    has undefined behavior.

    The function fgets can append the new line character '\n' to the entered string. You need to remove it. For example

    choix_utilisateur[ strcspn( choix_utilisateur, "\n" ) ] = '\0';
    

    Pay attention to that the conditions in if statements will be more readable if for example instead of this condition

    if(!strcmp(choix_utilisateur, "toto")){
    

    to write

    if( strcmp(choix_utilisateur, "toto") == 0 ){