Thread: comparing a password with strcmp

  1. #1
    Registered User
    Join Date
    Oct 2013
    Location
    Barcelona - Spain
    Posts
    18

    Unhappy comparing a password with strcmp

    Hi all!

    I'm a novice with C programming and i have to solve an error in the following code. The code works like you enter a password called "uoc"
    and it shows as OK. But surprisely when you entered another password as "Cambridge" it works fine too.

    I think that the problem is in the array declaration but i'm checking resources and no success!

    Any tip?

    Thanks so much!

    Please find the code:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    struct {
        char str[8];
        char ok;
    } data;
    
    
    int main(int argc, char *argv[])
    {
        data.ok = 0;
    
    
        while (data.ok == 0)
        {
            printf("Passwd? ");
            scanf("%s", data.str);
            if (strcmp(data.str, "uoc")==0) data.ok = 1;
        }
    
    
        printf("Passwd OK\n");
        return(0);
    }

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    You haven't enough space in data.str. "Cambridge" has 9 letters and therefore would take 10 chars to hold, since one extra is needed for the terminating null character. When you enter cambridge, the overflowing bytes get written over data.ok, causing it to be non-zero, causing your loop to terminate. You should give data.str at least, say, 32 chars, and you should read it like this to limit the chars read to 31:
    Code:
    scanf("%31s", data.str);
    Or you might want to use fgets instead.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  3. #3
    Registered User
    Join Date
    Oct 2013
    Location
    Barcelona - Spain
    Posts
    18
    Thanks so much for the light! Greetings.

  4. #4
    Registered User
    Join Date
    Oct 2013
    Location
    Barcelona - Spain
    Posts
    18
    It works perfectly! many thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. strcmp
    By lostandconfused in forum C Programming
    Replies: 3
    Last Post: 07-15-2010, 03:22 PM
  2. Replies: 2
    Last Post: 01-07-2009, 10:35 AM
  3. C++ Map vs. strcmp
    By Scarvenger in forum C++ Programming
    Replies: 16
    Last Post: 09-15-2007, 11:24 AM
  4. strcmp
    By Rob J in forum C++ Programming
    Replies: 1
    Last Post: 11-03-2004, 11:44 PM
  5. problem comparing strings with strcmp
    By mikefen in forum C Programming
    Replies: 2
    Last Post: 12-03-2001, 10:45 PM