سؤال

I have problem with strcmp function (same question is here, but there aren't good answers). If I compare 2 same strings, but one string is from structure, this string is wrongly "translated" to assembly code. Every char[] from structure are random 3 characters. Picture of strcmp.asm

#define CONS 60

typedef struct LinkCity{
    char city[CONS];           // i get this char[] from file by using fgets()
    struct LinkCity* next;
} tLinkCity;
/***************************************/
    typedef struct {
        int NumberOfCity;
        tLinkCity* Link;
        double** distances;
    } tDatabaze;
/***************************************/
int GetIndexOfCity(tDatabaze* db, char * city){

    printf("%s %s", db->Link->city, city); //   > Barcelona\n Barcelona (yes, here is a newline)
    str = strcmp(db->Link->city, city);    //   str = 1  (=it should be 0)
}
هل كانت مفيدة؟

المحلول

try removing the newline from the end of the string before comparing , here's a simple function to does that :

void removeNLine(char* string)
{
        int i ;
        for(i = strlen(string) ; i > 0 ; i--)
               if(string[i] == '\n')
                     string[i] = '\0';
}

نصائح أخرى

If I am not mistaken function fgets reads also the new line character into the array. So I think the reason of that two arrays are not equal each other is that one that was read by using fgets contains the new line character.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top