【发布时间】:2016-01-13 12:01:42
【问题描述】:
编辑
问题是我在程序的另一点使用了cin >>,因此流缓冲区中有一个尾随换行符。
所以主要的问题是关于 getline(),但为了更深入地了解它,您必须先查看我的代码。出于某种奇怪的原因,当我运行我的程序时,它第一次完美地运行了循环。然而第二次它跳过了我的getline(cin, inputMenu) 声明。是的,我知道这是一个非常非常基本的程序,而且我知道它没有其他错误,因为我已经测试了它的所有其他方面。 getline() 有什么我不知道的吗?
while (1)
{
// Reset the input each loop
inputMenu = "ABC";
// Menu
cout << "Menu\n P (Purchase)\n S (Shut down)" << "\n\n You decide: ";
/* I put this if statement as a test, to make sure that it always runs getline.
But for some odd reason when I run it I get this (see run below)*/
if(1)
getline(cin, inputMenu);
//Blah blah all the other stuff if they enter a P or S. (Not an infinite loop)
cout << "\nYou just earned " << inputYogurt << " stamps!"
<< " Bringing your grand total to " << numStamps << "!\n" << endl;
}
}
---------------------- Run --------------------
Menu
P (Purchase)
S (Shut down)
You decide: p
How many yogurts would you like to buy? 3
You just earned 3 stamps! Bringing your grand total to 3!
Menu
P (Purchase)
S (Shut down)
You decide: Menu <<<<<<<<<<<<<<<<<<<<<<<<<< Thats my error
P (Purchase)
S (Shut down)
You decide:
-------------------------------------------------------
它跳过 getline() 语句并再次运行循环。也许我不太了解 getline() ,因为显然这似乎是问题所在。我以为当你使用getline时,它必须等待用户输入,我错了吗?
【问题讨论】:
-
你的循环有问题,没完没了!!
-
@vishal 哈哈,我知道它没完没了。我有一个 if 语句可以跳出循环
-
不,它不会打破循环
标签: c++ while-loop getline