2

Edit

The issue was that I was using cin >> at another point in my program, and so there was a trailing newline in the stream buffer.


So the main question is about getline(), but in order to put it into perspective you have to see my code first. For some odd reason, when I run my program, it runs through the loop perfectly fine the first time. Yet the second time it skips my getline(cin, inputMenu) statment. And yes I know this is a very very basic program, and I know there are no other errors with it as I've tested literally every other aspect of it. Is there something about getline() that I don't know?

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:

-------------------------------------------------------

It skips the getline() statement and just runs the loop again. Maybe I don't understand getline() well enough, because clearly that seems to be the issue. I thought that when you use getline, it must wait for user input, am I wrong?

1 Answers1

1

It sometimes happens. The only way to deal with is to call cin.get() before cin.getline(). There is another method to call cin.flush() before cin.getline(), but it may not work.

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

or try to use

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

getline(cin, inputMenu);
Mykola
  • 3,343
  • 6
  • 23
  • 39