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