繁体   English   中英

getline和C ++中的while错误

[英]getline and while error in 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"));

我想知道为什么即使密码正确也出现“对不起...”的结果?

你好,世界! 请输入您的名字victor

请输入您的密码victor

胜利者

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

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM