[英]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.