Read a string with line break

Asked

Viewed 2,790 times

1

I need to compare two strings to see if they are equal.

One of them is in a vector of struct and was dealt with the fgets, so it’s a line break. The other one is informed by the keyboard.

I wonder if there is any function to read this second struct with line break, so I can compare it to the first.

3 answers

1

You can remove the line break in the first string (in a copy if necessary)

fgets(exemplo, sizeof exemplo, stdin); // assume no errors
len = strlen(exemplo);
if ((len > 0) && (exemplo[len - 1] == '\n')) {
    exemplo[--len] = 0; // remove quebra de linha e actualiza len
}

1

A solution, rather than changing one of the strings and remove line breaks, can go through implementing a comparison your.

An example of this comparison would be (based slightly on this reply):

// Retorna 0 se as strings forem iguais, -1 se forem diferentes
int CompareStrings(char* a, char* b);

int CompareStrings(char* a, char* b)
{
    int indexA, indexB;
    for(indexA = 0, indexB = 0; indexA < strlen(a) || indexB < strlen(b); ++indexA, ++indexB)
    {
        if(a[indexA] == '\n')
        {
            if(++indexA >= strlen(a))
                indexA = strlen(a);
        }

        if(b[indexB] == '\n')
        {
            if(++indexB >= strlen(b))
                indexB = strlen(b);
        }

        if((a[indexA] == '\0' || b[indexB] == '\0') || (a[indexA] != b[indexB]))
            break;
    }

    // Se ambos terminaram, as strings contidas são iguais.
    if( a[indexA] == '\0' && b[indexB] == '\0' )
        return 0;
    else
        return -1;
}

Example in Ideone tested.

-1

You can do strlen(variavel sem \n), then you copy the end of the string to the location of the \n and after that you can compare the strings.

Browser other questions tagged

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