Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing strings

Tags:

c

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:)

like image 811
user104108 Avatar asked Feb 12 '26 03:02

user104108


2 Answers

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

like image 74
overslacked Avatar answered Feb 14 '26 22:02

overslacked


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

password[index - 1] = '\0' 

after the do-while.

like image 39
akappa Avatar answered Feb 14 '26 22:02

akappa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!