strcmp gives unexpected results

4

I was practicing a bit of c to refresh my memory and there are some lines that are not working for me:

int main(){

    char nombre[20];
    int cont = 3;

    printf("Ingresa tu nombre de usuario\n");
    fgets(nombre,20,stdin);
    fflush(stdin);

    while(strcmp(nombre,"jorge")!=0){

        printf("Nombre de usuario incorrecto, ingrese nuevamente (Intentos restantes: %i)\n",cont);
        fgets(nombre,20,stdin);
        fflush(stdin);
        cont--;

    }


    if(cont==0) {
        printf("Se acabaron los intentos, vuelva mas tarde\n");
        exit(1);
    }

    printf("El programa continua normalmente\n");
}

Even though I put the valid name (jorge) it still enters the loop and I do not understand why

    
asked by Jorge DeSpringfield 09.10.2018 в 17:57
source

2 answers

3

You are probably passing the return character (Enter) within the chain. You can fix it by setting strncmp to 5 letters "jorge":

strncmp(nombre,"jorge",5)!=0

or directly concatenated the return character CR (\ n):

strcmp(nombre,"jorge\n")!=0
    
answered by 09.10.2018 / 18:09
source
0

And if you try this?:

int main () {

char nombre[20];
int cont = 3;

printf("Ingresa tu nombre de usuario\n");
scanf("%s",nombre);
fflush(stdin);

while((strcmp(nombre,"jorge")!=0) && (cont>0)){

    printf("Nombre de usuario incorrecto, ingrese nuevamente (Intentos restantes: %i)\n",cont);
    scanf("%s",nombre);
    fflush(stdin);
    cont--;

}


if(cont==0) {
    printf("Se acabaron los intentos, vuelva mas tarde\n");
    exit(1);
}

printf("El programa continua normalmente\n");
system("pause");
return 0;

}

In the while, I add the condition that the attempts are greater than 0.

    
answered by 09.10.2018 в 18:14