简体   繁体   中英

getline and while error in C++

Hi I am a beginner for C++, and here is my practice code:

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

Please enter your password 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.

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.

Also, the logic AND operator is && and not & .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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