Friday, July 31, 2009

C++ whats wrong with my code?

I'm using boolean variables in conjunction with coditional operators to make a short sharp password program, but theres a problem with my script...its seems that despite the correct input, it selects the "Invalid password" condition...whats wrong?





#include %26lt;cstdlib%26gt;


#include %26lt;iostream%26gt;


#include %26lt;string%26gt;





using namespace std;





int main(int argc, char *argv[])


{


string password = "tong";


string result;





cout %26lt;%26lt; "Please enter password" %26lt;%26lt; endl;


cin %26gt;%26gt; password;





result = (password=="tong") ? "Access granted" : "Acess denied";





cout %26lt;%26lt; result %26lt;%26lt; endl;





system("PAUSE");


return EXIT_SUCCESS;


}

C++ whats wrong with my code?
First off, dont bother initially assigning password the "tong" value.





Second, instead of...





result = (password=="tong") ? "Access granted" : "Acess denied";


cout %26lt;%26lt; result %26lt;%26lt; endl;





try this...





if (password == "tong") { cout%26lt;%26lt;"Access Granted"; }


else { cout%26lt;%26lt;"Access Denied"; }





Might just be a problem of syntax.
Reply:Hi, your code is fine, although it's pointless to initialize password to something if you are going to change it afterwards. I tried it on a mac and it produces the expected behaviour. One thing I would try to debugg is to output in the screen the value of password by doing cout%26lt;%26lt;password%26lt;%26lt;endl;





If it doesn't work it could be a compiler problem in which case you might need to upgrade it. What operating system are you using?
Reply:don't initialize password





It worked fine for me...
Reply:You must use the compareTo method of string ..





result = (password.compareTo("tong") == 0) "Access granted" : "Access denied";





the string object not define an overload for operator == (const char*)


No comments:

Post a Comment