![]() |
| ||
| My "if" is not good hi everyone, hope u r all feeling fine :mrgreen: this is my program: #include <stdio.h> int main() { char pass[12]; printf("Enter Password: "); gets(pass); if (pass == "neo") { printf ("ini"); } else printf("Wrong"); return 0 ; } when i enter "neo" as password, it does the "wrong" thing :( how can i correct it |
| ||
| Re: My "if" is not good try this: if(strcmp(pass,"neo")==0) printf("ini"); else printf("Wrong"); strcmp() compares two strings if strings are equal then it returns 0; |
| ||
| Re: My "if" is not good thanks (they told me to lengthen my message) |
| ||
| Re: My "if" is not good Shalin is right, what you were comparing was the ADDRESS of pass with the ADDRESS of the quoted literal "neo". They would never be the same. If you use std::string instead, it defines an '==' operator that does a strcmp() for you, so you may see something like this in some code: std::string s; . . . if (s == "neo") and that WORKS because s isn't a char pointer but a class with an '==' operator defined. |
| ||
| Re: My "if" is not good try this............ #include <stdio.h> #include <iostream.h> int main() { char pass[12]; printf("Enter Password: "); gets(pass); if (pass == "neo") cout<<"ini"; else cout<<"Wrong"; return 0 ; } |
| ||
| Re: My "if" is not good well, that, too would fail. Shalin's answer would be the simplest. |
| ||
| Re: My "if" is not good Hi everyone, I rewrote your program a bit and seems to work for me #include <stdio.h> void main(void) { String pass; printf("Enter Password: "); scanf("%s",&pass); if (pass == "neo") { printf ("ini"); } else { printf("Wrong"); } } I hope this helps you Yours Sincerely Richard West |
| ||
| Re: My "if" is not good Hello, It is a bad idea to use mathematical equations (==) compare strings! This is why there is a standard library to do it... strcmp is the traditional correct way to do it. Might as well learn the proper way to do it....or that portable code may bomb out on the next compiler release. If it is worth doing, do it correctly! Christian |
| ||
| Re: My "if" is not good Shalin's method is the ideal one. However, if you don't want to use strcmp() for some reason, there's always a manual, lenghtier way to do it: #include <iostream.h> |
| ||
| Re: My "if" is not good thanks to you all, really make me feel happy |
| All times are GMT -4. The time now is 12:02 pm. |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC