1
我遇到了getline函數的問題。如果我的代碼沒有詳細描述到stackoverflow語法,我提前道歉。我所遇到的是當我運行addMember()時,它會提示用戶輸入名稱,然後檢查它是否已經存在。一旦通過,它就會繼續詢問用戶密碼。如果一切順利,它會被推入矢量成員列表中。從那裏我應該可以退出並以新會員身份登錄。當我立即調用此功能時打印的內容是「請輸入成員名稱:輸入所需密碼:」。它完全跳過了允許用戶輸入名稱並直接輸入密碼的點。我知道我需要使用cin.ignore(1000,'\ n'),但所有這些都會從成員列表中刪除名稱或密碼。例如:當我輸入用戶名時,它會正確讀入,但密碼讀入前一個getline結尾處的換行符。有沒有解決這個問題的方法,除了在主要的方面進行修改?請幫忙!謝謝!cin.ignore的getline問題
void Staff::addMember() {
string name;
string password;
bool alreadyexists = false;
cout << "Please enter name of member: ";
getline(cin, name);
if (name.length() == 0) {
cout << "You must enter a name. Please try again." << endl;
addMember();
} else {
for (unsigned int i = 0; i < memberlist.size(); i++) {
if (memberlist[i].getName() == name) {
alreadyexists = true;
cout << "That user already exists. Please try again." << endl;
addMember();
}
}
}
if (alreadyexists == false) {
cout << "Enter desired password: ";
getline(cin, password);
cout << password;
Member newMember(name, password);
cout << "At time of instance " << newMember.getName() <<endl;
memberlist.push_back(newMember);
cout << "A new member has been added!" << endl;
for (unsigned int i = 0; i < memberlist.size(); i++)
{
cout << memberlist[i].getName() << "\t"<< memberlist[i].getPassword() << endl;
}
cont();
// }
}
displayMenu();
}