1

I'm a first semester C++ student and in class we are building a BMI calculator (Win32 Console Application). I've gotten everything to work just fine, except for one of the instructions, which is wait for user to press enter to close application.

I had success using the system("PAUSE"); statement but in the past I would declare a string variable, like for example, initialize string genVar; and then use getline(cin, genVar); and when the user pressed Enter, the application would close, but it didnt work this time. The application would simply close. It worked just fine with pause, but not with getline().

Is using getline() for this purpose bad practice? Anyone have any clue why it didn't work?

Thank you in advance!

  • There's probably a leftover newline in the input buffer: http://stackoverflow.com/search?q=%5Bc%2B%2B%5D%20getline%20skipping – chris May 16 '13 at 04:18

3 Answers3

0

std::cin and std::getline do not mix well in general, you usually want to stick to one or the other in a program to avoid input errors and bugs. Your getline probably is grabbing a left over input from as earlier std::cin. I would recommend using this:

  std::cout << "Press ENTER to continue...";
  std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

  return 0;
  }

you'll need to include <limits> for this to work correctly.

Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177
0

you can also use the getch() function in the place of std::getline() IMHO

0

I know this is an old post, but look at the solution which I posted in this question:

C++ Multiple Program Issues (rand, conversion, crashing)

It explains (as chris mentioned in a comment) that getline tends to leave in a new line character in the buffer, which needs to be cleared and reset. Answer above explains it.

Community
  • 1
  • 1
Geoherna
  • 3,523
  • 1
  • 24
  • 39