Read a string with line break

1

I need to compare two strings to see if they are the same.

One of them is in a struct vector and has been dealt with fgets , so it is broken. The other is informed by the keyboard.

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

    
asked by anonymous 07.12.2014 / 23:11

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
}
    
07.12.2014 / 23:37
1

A workaround, instead of changing one of the strings and removing line breaks, may implement a comparison of yours.

An example of such a comparison would be (based slightly on this response ):

// 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] == '
// 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] == '%pre%' || b[indexB] == '%pre%') || (a[indexA] != b[indexB]))
            break;
    }

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

Example on Ideone with tests.

    
08.12.2014 / 14:38
-1

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

    
10.05.2015 / 02:42