首页 文章

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

提问于
浏览
2

这个问题在这里已有答案:

Edit

问题是我在我的程序中的另一个点使用了 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 回答

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

相关问题