【问题标题】:Can getline() be skipped w/o user input? [duplicate]可以在没有用户输入的情况下跳过 getline() 吗? [复制]
【发布时间】: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


【解决方案1】:

有时会发生。唯一的处理方法是在cin.getline() 之前调用cin.get()。还有另一种方法可以在cin.getline() 之前调用cin.flush(),但它可能不起作用。

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);

【讨论】:

  • 还是没用 :'( 我想用cin &gt;&gt;,但我没有足够的知识/不知道你是否可以将它应用到字符串中。
  • 您可以尝试添加另一个额外的 cin.get() 或 cin.flush()
  • 或者只使用gets或scanf
  • cin &gt;&gt; 可以应用于字符串,但它只输入空格前的第一个单词
猜你喜欢
  • 2011-04-13
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 2013-08-01
  • 2016-01-25
  • 1970-01-01
  • 2017-04-29
  • 1970-01-01
相关资源
最近更新 更多