我在for循环中有以下代码。当它第一次通过时,运行得很好。然而,当它再次运行时,它会在cin.ignore之前停止,我必须先按Enter键才能输入输入。有什么理由呢?感谢。
cin.ignore(100, '\n');
string input;
getline(cin, input);
编辑:
以下是代码的全部内容:
请注意,矢量餐厅中有16个字符串。函数ifOddNumberOfRestaurants如下:
void ifOddNumberOfRestaurants(vector<string> restaurants){
cout << "To begin the tournament, please add one more restaurant to the list: ";
cin.ignore(1000, '\n');
string newRestaurant;
getline(cin, newRestaurant);
restaurants.push_back(newRestaurant);
}
有问题的代码:
else if ( option == 5 ) {
int numberRestaurants = restaurants.size();
int evenOrOdd = numberRestaurants % 2;
if (evenOrOdd == 1){
ifOddNumberOfRestaurants(restaurants);
}
vector<string> battleRestaurants(restaurants);
int stop = 0;
while ( stop == 0 ){
double half = battleRestaurants.size()/2;
int option1 = 0;
int option2 = 1;
int match = 1;
for(int i = 0; i < half; i++){
cout << "Match " << match << "/" << half << " --- " << battleRestaurants[option1] << " *OR* " << battleRestaurants[option2] << "? ";
match++;
cout << "\nBEFORE IGNORE\n";
cin.ignore(100, '\n');
cout << "\nAFTER IGNORE\n";
string winner;
getline(cin, winner);
if ( winner == battleRestaurants[option1]){
battleRestaurants.erase(battleRestaurants.begin() + option2);
}
else if ( winner == battleRestaurants[option2]){
battleRestaurants.erase(battleRestaurants.begin() + option1);
}
option1++;
option2++;
cout << "Postion of i: " << i << "\nPosition of Option 1: " << option1 << "\nPosition of Option 2: " << option2 << "\n" << endl;
printRestaurants(battleRestaurants);
}
}
}
答案 0 :(得分:0)
我认为你的问题是你有cin.ignore(100,&#39; \ n&#39;);如果你不需要它删除它,你的代码应该可以正常工作。我只尝试了那个部分的一小段片段,它运行良好。 EX:`矢量餐厅;
int numberRestaurants = restaurants.size();
int evenOrOdd = numberRestaurants % 2;
for (int i = 0; i < 5; i++)
{
if (evenOrOdd == 1){
cout << "To begin the tournament, please add one more restaurant to the list: ";
//cin.ignore(100, '\n');
string newRestaurant;
getline(cin, newRestaurant);
restaurants.push_back(newRestaurant);
}
}
删除忽略这就是为什么你必须在接受任何其他内容之前按Enter键,因为它将忽略前100个字符或新的行,以先到者为准。