Monday, May 24, 2010

Please help me in this password code ?

Hi


I am inputing same password as akku . why its showing "wrong". Please tell me the mistake and giuide me in this code#include%26lt;stdio.h%26gt;


#include%26lt;conio.h%26gt;





main()


{


char c;


char ppp[20] = "akku"; // correct password


char password[20];


int cnt=0;





printf("password:");





while( (c=getch()) != 13 ) // 13 is the code for enter


{


password[cnt] = c;


printf("*");


cnt++;


}


password[cnt] = '\0';





if(password==ppp)


printf("correct");


else


printf("wrong");





getch();


}

Please help me in this password code ?
Change if(password==ppp) to if(!strcmp(password,ppp)) .


Characters (strings) in C/C++ can not be compared with == operator . You have to use strcmp function instead .





Don't forget to include string.h header file .
Reply:An elaboration on the last answer:


When you create ppp[20] and password[20], you request the compiler to create these two lines:


char *ppp, *password;


ppp=new char[20];


password=new char[20];


This causes the name of the array to actually be a pointer to its first element, meaning the expansion of the expression:


a[x]


is actually:


*(a+x)


which works because of pointer arithmetic.


When you do the equality, it can be guaranteed that ppp and password do NOT have the same address, which happens to be what you are comparing. The only work around is to compare size then loop for every character. Luckily, strcmp(const char *, const char *) %26lt;string.h%26gt; does this for you, and returns 0 for equal strings, -1 for "less than", and 1 for "greater than".


No comments:

Post a Comment