getline和C ++中的错误

时间:2018-01-25 03:26:56

标签: c++

您好,我是C ++的初学者,这是我的练习代码:

cout << "Hello World! "<< "Please enter your name" << " ";
//cin >> i;
getline(cin, mystring);
stringstream(mystring) >> name;
cout << "Please enter your password"<< " " ;
getline(cin, mystring);
stringstream(mystring) >> password;
cout << password << endl;

do {
    cout << "Sorry, your password does not match your name, please enter the password again" << " " << endl;
    getline(cin, mystring);
    stringstream(mystring) >> password;
} while (!(name == "victor" & password == "victor"));

我想知道为什么结果如下&#34;抱歉......&#34;即使密码是正确的?

  

Hello World!请输入您的姓名victor

     

请输入您的密码victor

     

胜利者

     

抱歉,您的密码与您的姓名不符   再次输入密码

1 个答案:

答案 0 :(得分:3)

do...while循环总是至少执行一次,因为底部的测试是在循环结束时执行的。

因此,您将始终至少看到有关错误密码的消息。如果只想在条件为真时执行循环,请使用常规while循环,条件位于顶部。

此外,逻辑 AND 运算符为&&而非&

while (!(name == "victor" && password == "victor"));
{
    cout << "Sorry, your password does not match your name, please enter the password again" << " " << endl;
    getline(cin, mystring);
    stringstream(mystring) >> password;
}