0

I tried std::getchar();, cin::get(); and system ("sleep");, but nothing stops the console from closing, because it seems, that all of these functions misinterpret the pressed enter key that was supposed to confirm input for scanf. How can I prevent the console from closing with a "Press enter / any key to close" behavior after scanf? I don't want to use functions stopping the console totally from doing something for some time (like sleep) or non-portable functions (like system ("sleep")), unless such functions are the only ways.

int main () {
    wchar_t *user = new wchar_t[30];
    wscanf (L"%30ls", user);
    // Process data... (very short time)

    std::getchar ();

    return 0;
}

IDE: Visual Studio 2013 (12.0) Express I don't know the compiler. I created an empty C++ project and didn't change any settings.

Cubi73
  • 1,791
  • 3
  • 28
  • 45
  • Show us the code please. – David G Aug 06 '14 at 20:07
  • 1
    Have you tried invoking `std::getchar()` twice in a row? – merlin2011 Aug 06 '14 at 20:07
  • 1
    You could use `scanf` again. – NetVipeC Aug 06 '14 at 20:07
  • Which IDE/compiler are you using? – nasser-sh Aug 06 '14 at 20:07
  • 2
    possible duplicate of [Why is the Console Closing after I've included cin.get()?](http://stackoverflow.com/questions/6398229/why-is-the-console-closing-after-ive-included-cin-get) – uchar Aug 06 '14 at 20:16
  • The possible duplicate has the same problem. After calling `scanf` there is a trailing `\n` that gets read by `cin.get()`, `system("pause")` and `std::getchar()`. So merlin's solution (using `std::getchar()` twice works pretty well. – Cubi73 Aug 06 '14 at 20:21
  • Don't code it in. Run the program from the command line like it's meant to be run, or if running from the IDE, tell the IDE to pause it. – chris Aug 06 '14 at 20:26

2 Answers2

1

Do it like this:

// do your stuff here

// prevent console from closing
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.get();
char8_t
  • 300
  • 1
  • 7
  • Because this answer works as well as merlin's solution (using `getchar()` twice, you get the correct answer. – Cubi73 Aug 06 '14 at 20:24
-1

Use system("pause"); at the end of main() function.

Subodh S
  • 105
  • 1
  • 4