tags:

views:

94

answers:

6
+1  Q: 

comparing strings

considering this piece of code

    char *pass="test";
    int keyPressed;
    char *password=(char *)malloc(PASS_LENGTH*sizeof(char));
    int index=0;
    printf("Enter the password please\n");
    do
    {
     keyPressed=getch();
     password[index++]=keyPressed;
    }
    while(keyPressed!=13);
    int result=strcmp(pass,password);

i think you understand what i want to do :)
i read in *password "test" but result is not 0, some explanation would be good:)

+5  A: 

You have to remove the last character and "close" the string: put

password[index - 1] = '\0'

after the do-while.

akappa
I think you meant '\0'
Ben
i think he meant "\0" (double quotes)
Kris
ops...Corrected :)
akappa
@Kris Double quotes is a string (multiple characters), single quotes is a single character. So single quotes is correct here.
Stephen Darlington
A: 

Looks like it would be "test\n" because you already added keyPressed. Thereby also overflowing the password variable.

Kris
A: 

You should malloc PASS_LENGTH+1 and set password[index] = 0 at before the last line of code. as strcmp and other C str routines work with ASCIIZ strings

Anton Kazennikov
A: 

The carriage return is included on the end of password.

joshdick
+6  A: 

Since I think this is homework ... try writing out the strings after they've pressed Enter and see if you can see a difference.

overslacked
+1  A: 

akappa's suggestion will fix the strcmp problem you're seeing.

Also note you're mallocing a finite amount of memory but when writing this memory you don't check against the size of the allocated block. The code as written will allow writing passed the end of "password".

diciu