【发布时间】:2018-04-14 03:55:06
【问题描述】:
在下面的代码中,我一直试图让它检查多个参数(当检查用户名和密码是否正确时)。
string username;
string password;
cout << "Hello there. To access this program, please put in your user name and password." << endl;
cout << "Username: ";
cin >> username;
cout << "Password: ";
cin >> password;
if(username != "admin", password != "therealpassword"){
do{
cout << "Username or password is incorrect." << endl;
cout << "Username: ";
cin >> username;
cout << "Password: ";
cin >> password;
}while(username != "admin", password != "therealpassword");
}
无论出于何种原因,在运行程序时,我输入了错误的用户名,但输入了正确的密码,它允许我登录。在 (do...while) 部分,如果我输入了错误的用户名,但再次输入了正确的密码,即使用户名不正确,我仍然可以正确登录。我怎样才能得到它来检查用户名和密码?感谢您提供任何和所有帮助。
【问题讨论】:
-
只是为了让代码的行为更清晰:逗号运算符
,是一个序列点。换句话说,如果您在表达式中写入a, b(就像您在if条件中所做的那样),它将评估a,丢弃它的值,评估b,然后返回它的值。这就是为什么只要密码正确,您的条件总是被评估为true。
标签: c++ if-statement do-while