可以跳过没有用户输入的getline()吗?

时间:2015-10-15 06:42:32

标签: c++ while-loop getline

修改

问题是我在程序的另一个点使用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时,它必须等待用户输入,我错了吗?

1 个答案:

答案 0 :(得分:1)

有时会发生。唯一的处理方法是在cin.get()之前致电cin.getline()。还有另一种方法可以在cin.flush()之前调用cin.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)*/


      cin.get(); // add extra input
      getline(cin, inputMenu);

      //Blah blah all the other stuff if they enter a P or S.

         cout << "\nYou just earned " << inputYogurt << " stamps!"
            << " Bringing your grand total to " << numStamps << "!\n" << endl;
      }
   }

或尝试使用

cin.ignore(1000, '\n');

getline(cin, inputMenu);