C - String comparison with strcmp does not work

Asked

Viewed 18 times

-1

Guys, I’m trying to compare a string entered by the user in a dynamic array of strings with a predefined string. In the DO-WHILE loop the repetition should end as the string the user enters for FIM, but this does not happen. What could be?

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


int main () {

    //declaracao de variaveis
    int linhas = 100, colunas = 500, controlador = 0;
    char limite[ ] = "FIM";
    char **frases = (char **) malloc (linhas * sizeof(char *));

        for (int i = 0 ; i < linhas ; i++)
            frases[i] = (char *) malloc (colunas * sizeof(char));

    //ler frases
    printf("\n");

    do {
        fgets(frases[controlador], colunas, stdin);
        controlador++;

    } while (strcmp(frases[controlador - 1], limite) != 0); 

    //liberar ponteiro
    for (int i = 0 ; i < linhas ; i++)
        free(frases[i]);

    free(frases);

    return 0;  //finalizar o programa

}

1 answer

1


The typed string, received by fgets(), contains the end-of-line character ( n, r or r n, depending on the operating system). Your comparison string would have to include this character, or else you do the test a little differently.

On Linux, making the comparison string equal to "FIM n" solved the problem.

  • 1

    That’s exactly what it was! I used the strcspn function to find the position of n in the inserted strings, recorded it in a variable and used it to assign the null value instead of n and is now 100% functional and ready. Thank you so much!!!

Browser other questions tagged

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