I'm VERY inexperienced in programming, I'm just learning the very basics. Anyways, I just figured out how to add a "pause" line to keep the program from closing as soon as I run it, but now there's a nasty "Press any key to continue" after my text. Is there a way to hide this? Thanks in advance. :)

Recommended Answers

All 6 Replies

I assume you're using system ( "PAUSE" ) . My first inclination is to say that this solution is a bad idea anyway, and if it doesn't do exactly what you want, that's all the better for convincing you not to use it. :D

The usual recommendation for pausing a program from an IDE that terminates the hosting console when the program ends is to ask for input. For example, the following code won't terminate until you press the Enter key:

#include <iostream>

int main()
{
  std::cout<<"Hello, world!\n";
  std::cin.get();
}

You'll eventually have problems with existing data in the stream causing this not to work, but we have a sticky on this forum that teaches you how to deal with that.

Ahh, thanks. Solved my problem completely.

You can also do:

#include <iostream>
#include <conio.h>

int main()
{
   std::cout << "HELLO WORLD!!!!!!!111";
   getch();
}

>You can also do:
You could, if you wanted to be wrong most of the time. conio.h and getch are non-portable, so the majority of compilers won't support them.

Ok

For a windows solution, you could try this which will allow the user to press any key to continue (not just enter):

void Pause(char *message = "Press any key to continue . . . ") {
  std::cout << message;
  HANDLE hStdin; 
  DWORD cNumRead; 
  INPUT_RECORD irInBuf[1];

  if ( HANDLE(hStdin = GetStdHandle( STD_INPUT_HANDLE )) == INVALID_HANDLE_VALUE )
    return;

  while ( true )  { 
    if (! ReadConsoleInput( hStdin, irInBuf, 1, &cNumRead) )
      return;

    for (DWORD i = 0; i < cNumRead; ++i)
      if ( irInBuf[i].EventType == KEY_EVENT && irInBuf[i].Event.KeyEvent.bKeyDown ) {
        std::cout << '\n';
        return;
      }
  }
}

To remove the message, simply call it like this.

Pause("");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.