我需要防止垃圾留在緩衝區中,因爲在用戶輸入的菜單中調用的功能中使用了開關盒菜單的值。在cin緩衝區中留下的垃圾
菜單代碼
void menu()
{
bool done = false;
string input;
while(!done)
{
cout << "Welcome to the DVD database." << endl;
cout << "1. Add A DVD" << endl;
cout << "2. Delete a DVD." << endl;
cout << "3. Edit a DVD." << endl;
cout << "4. List By Category." << endl;
cout << "5. Retrieve by a DVD by Title." << endl;
cout << "6. Display collection by year" << endl;
cout << "7. Display collection by title" << endl;
cout << "-999. Exit program" << endl;
cout << "Please choose an option by entering the corresponding number" << endl;
cin >> input;
int value = atoi(input.c_str());
switch(value)
{
case 1:addDVD(); break;
case 2:deleteDVD(); break;
// case 3:editDVD(); break;
case 4:listByCategory();break;
case 6:displayByYear();break;
case 7:displayByTitle();break;
case -999: writeToFile(); exit(0); break;
default : cout <<"Invalid entry"<< endl; break;
}
}
}
void retrieveByTitle()
{
string search;
int size = database.size();
int index = 0;
bool found = false;
cin.ignore();
cout << "Please enter the title of the DVD you would like to retrieve: " << endl;
getline(cin,search);
cout << search;
while(!found && index<size)
{
if(database.at(index)->getTitle().compare(search)==0)
{
cout << database.at(index)->toString();
break;
}
}
cout << endl;
}
如果5在菜單中進入,程序跳過
你爲什麼要讀入一個字符串和使用的atoi,而不是僅僅讀入一個數? (int x; cin >> x;) – tohava
當我在menu()方法中輸入5時(要進入retrieveByTitle()方法,當由retrieveByTitle()請求時,我無法輸入任何內容,當我在菜單()中做出選擇時,在retrieveByTitle中調用getline()時使用。 –
剩下的是你正在按下來讀取輸入的'\ n'(或Enter),所以當程序要求標題爲' getline()'讀入一個換行符'\ n'。你需要考慮如何阻止這個... –