简体   繁体   English

getline和C ++中的while错误

[英]getline and while error in C++

Hi I am a beginner for C++, and here is my practice code: 嗨,我是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"));

I wonder why the result is as follows that "Sorry..." appears even the password is correct? 我想知道为什么即使密码正确也出现“对不起...”的结果?

Hello World! 你好,世界! Please enter your name victor 请输入您的名字victor

Please enter your password victor 请输入您的密码victor

victor 胜利者

Sorry, your password does not match your name, please enter the password again 抱歉,您的密码与您的姓名不符,请再次输入密码

A do...while loop always executes at least once because the test at the bottom is performed at the end of the loop. do...while循环始终至少执行一次,因为底部的测试是在循环结束时执行的。

So you will always see the message about the wrong password at least once. 因此,您将始终至少看到一次有关密码错误的消息。 If you want to execute the loop only when the condition is true, use a regular while loop with the condition at the top. 如果只想在条件为真时才执行循环,请使用常规的while循环,条件在顶部。

Also, the logic AND operator is && and not & . 同样,逻辑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