Justplayit94
Justplayit94

Reputation: 423

Strcmp does not do the comparing

Why isn't the comparing between the strings work? I know for a certain that the user strings do not have any endlines at the end of them, but still I get that the username is not accepted.

char user[24];
int userLog = -1;

FILE  *usernames;
usernames = fopen("usernames.cfg", "r");

if (usernames == NULL){
    perror("usernames - err");
    return(-1);
}

while(fgets(user, sizeof(user), usernames) !=NULL){

    strtok(user, "\n");
    printf("%s -- %s\n", user, possibleUsername);

    // First edition of question contained:
    // if((possibleUsername, user) == 0)
    // Still having problems with this version:
    if(strcmp(possibleUsername, user) == 0)
        userLog = 1;
    else 
        userLog = 0;

}

if(userLog == 1) printf("Username accepted:   %s\n", possibleUsername);
else if(userLog == 0) printf("Username doesn't exist in the database.\n");
fclose(usernames);

usernames.cfg:

user
justplayit
etc

Upvotes: 1

Views: 229

Answers (2)

Filip Czaplicki
Filip Czaplicki

Reputation: 188

I suppose it should be

if(strcmp(possibleUsername, user) == 0)

Because the expression

(possibleUsername, user) == 0

is equal to

user == NULL

EDIT

Change

int userLog = -1;

to

int userLog = 0;

and delete

else
    userLog = 0;

Upvotes: 3

user5505150
user5505150

Reputation:

Try this:

int main(int argc, char** argv)
{   
    char user[24];
    int userLog;
    FILE* usernames;
    char* userPtr;

    usernames = fopen("usernames.cfg", "r");
    if (usernames == NULL)
    {
        perror("Usernames config not found or read protected");
        return EXIT_FAILURE;
    }

    while(fgets(user, sizeof(user), usernames) != NULL)
    {
        userPtr = strtok(user, "\n");
        if (userPtr != NULL) 
        {
            printf("Username in file => %s", userPtr);
            if (strcmp(userPtr, "find me") == 0)
            {
                userLog = 1;
                break;
            }
            else
            {
                userLog = 0;
            }
        }
    }

    if (userLog)
    {
        printf("User find me accepted");
    }
    else
    {
        printf("User find me not in database");
    }

    fclose(usernames);

    return EXIT_SUCCESS;
}

Its the same program you wrote, but I use an extra pointer returned from strtok to check if any token is found. Comparing this token with a "zero-terminated" string, like your possibleUsername should be, works for me. If possibleUsername is a fixed length character array you are adviced to use strncmp and set the length of the string to compare e.g. strncmp(userPtr, possibleUsername, length) == 0. What could also be the problem if the usernames.cfg file is saved with \r\n so strtok would return "username\r" instead of "username". Maybe you could debug your program and check the buffer of user what content it has. Hope it helps.

Upvotes: 1

Related Questions