By Adam P


2010-03-27 14:29:41 8 Comments

Lately, I've been trying to learn C++ from this website. Unfortunately whenever I try to run one of the code samples, I see that program open for about a half second and then immediately close. Is there a way to stop the program from closing immediately so that I can see the fruits of my effort?

30 comments

@Dmitriy Suserov 2014-12-19 10:26:34

simply

#include <cstdio>

    int main(){
        // code...
        std::getchar();
        std::getchar();
        return 0;
    }

@kaya3 2019-11-13 18:34:01

Please add at least a short explanation of why this solves the problem.

@Kursat Turkay 2017-08-28 15:50:25

just use cin.ignore() right before return 0; twice

main()
  {
  //your codes 

  cin.ignore();
  cin.ignore();

  return 0;
  }

thats all

@aj.toulan 2018-01-21 20:00:12

I normally do this something like this. cin.ignore(); cin.get();

@Ruan 2017-04-05 07:11:14

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

using namespace std;

int main()
{

    cout << "Press any key to continue...";
    getch();

    return 0;
}

I didnt notice anyone else post this so here it is.

@Yksisarvinen 2018-05-23 06:45:33

I'd add that conio.h is a Windows specific header and may not be available at every machine (or you might need to link it separately, which is an overkill).

@César N. 2018-11-26 21:02:26

Working. just needed to change getch(); to _getch(); since it became depreceated

@Tommaso Thea Cioni 2017-01-01 20:50:03

The most proficient way to do this is by leaving

while (true) {
}

at the end of the last function your program executes.

(In case someone who doesn't know what that means, it's basically a never ending loop. Since nothing is contained inside the brackets, it will continue to do nothing forever, it literally does NOTHING, but for the program it's a task like another).

@Cœur 2017-03-19 17:21:55

Similar idea to yeh answer, just minimalist alternative.

Create a batch file with the following content:

helloworld.exe
pause

Then use the batch file.

@Mohammed Nouh 2017-02-14 15:28:41

Use #include "stdafx.h" & system("pause"); just like the code down below.

#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
    std::cout << "hello programmer!\n\nEnter 2 numbers: ";
    int x, y;
    std::cin >> x >> y;
    int w = x*y;
    std::cout <<"\nyour answer is: "<< w << endl;
    system("pause");
}

@melpomene 2019-01-06 21:18:53

system is declared in <cstdlib>, not stdafx.h.

@anony 2016-04-03 14:47:25

Instead of pressing the run button, press CTRL and F5 at the same time, it will give you the press any key to continue message. Or type "(warning use this only for testing not actual programs as an antiviruses don't like it!!!!)" at the end of your main function but: (warning use this only for testing not actual programs as an antiviruses don't like it!!!!)

@user5657236 2015-12-12 08:37:37

I tried putting a getchar() function at the end. But it didn't work. So what I did was add two getchar() functions one after another. I think the first getchar() absorbs the Enter key you press after the last data input. So try adding two getchar() functions instead of one

@GuestPerson00001 2015-12-11 20:36:01

I just do this:

//clear buffer, wait for input to close program
std::cin.clear(); std::cin.ignore(INT_MAX, '\n');
std::cin.get();
return 0;

Note: clearing the cin buffer and such is only necessary if you've used cin at some point earlier in your program. Also using std::numeric_limits::max() is probably better then INT_MAX, but it's a bit wordy and usually unnecessary.

@wernersbacher 2016-11-21 08:31:04

It works, but the return 0; won't execute if I use this code.

@QMaster 2015-06-16 14:45:40

I used cin.get() and that is worked but one day I needed to use another cin.get([Array Variable]) before that to grab a ling string with blank character in middle of. so the cin.get() didn't avoid command prompt window from closing. Finally I found Another way: Press CTRL+F5 to open in an external window and Visual Studio does not have control over it anymore. Just will ask you about closing after final commands run.

@Mr. Underhill 2011-01-29 03:12:07

If you are using Microsoft's Visual C++ 2010 Express and run into the issue with CTRL+F5 not working for keeping the console open after the program has terminated, take a look at this MSDN thread.

Likely your IDE is set to close the console after a CTRL+F5 run; in fact, an "Empty Project" in Visual C++ 2010 closes the console by default. To change this, do as the Microsoft Moderator suggested:

Please right click your project name and go to Properties page, please expand Configuration Properties -> Linker -> System, please select Console (/SUBSYSTEM:CONSOLE) in SubSystem dropdown. Because, by default, the Empty project does not specify it.

@Jesse Pepper 2012-03-14 06:29:32

What if it's not a console app?

@Jonathan 2012-09-06 18:57:21

This is the correct answer. Thank you.

@Kyle Smith 2014-01-20 03:49:18

This is totally the best answer, the other answers are hacks.

@Jonathan Mee 2014-12-18 13:56:07

@Mr.Underhill This will only work if you launch without the debugger (Ctrl+F5).

@user2023370 2016-01-03 21:26:57

This doesn't work for Makefile projects.

@Alex Jansen 2018-08-31 21:23:40

This doesn't work for CMake projects either.

@Poniros 2019-04-13 11:52:50

Apart from being the only non-hack solution, this is also the only way to see prints from main stack objects destructors.

@MicroVirus 2015-05-18 20:45:00

For Visual Studio (and only Visual Studio) the following code snippet gives you a 'wait for keypress to continue' prompt that truly waits for the user to press a new key explicitly, by first flushing the input buffer:

#include <cstdio>
#include <tchar.h>
#include <conio.h>

_tprintf(_T("Press a key to continue "));
while( _kbhit() /* defined in conio.h */ ) _gettch();
_gettch();

Note that this uses the tchar.h macro's to be compatible with multiple 'character sets' (as VC++ calls them).

@Daan 2015-05-18 14:39:35

Start in debug mode, run code with F5 to stop your console app, don't click on red cross but press CTRL-break and you'll hit all breakpoints in the end of your program.

@kamatsahas 2015-05-05 07:43:45

simply put this at the end of your code:

while(1){ }

this function will keep going on forever(or until you close the console) and will keep the console it from closing on its own.

@Ali Asgari 2015-01-15 00:52:11

Include conio.h and at the end of your code, before return 0, write _getch();

@lierosk 2014-12-18 11:20:22

I'm putting a breakpoint at the last return 0 of the program. It works fine.

@Ravi Dhoriya ツ 2014-12-18 11:58:09

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post.

@lierosk 2014-12-18 13:54:39

How this doesnt provide answer? Im in exactly same situation like author of a question and this helps.

@PatThaCoder 2013-11-21 15:16:34

If you are running Windows, then you can do system("pause >nul"); or system("pause");. It executes a console command to pause the program until you press a key. >nul prevents it from saying Press any key to continue....

@yeh 2013-05-14 11:07:40

You could always just create a batch file. For example, if your program is called helloworld.exe, some code would be:

@echo off
:1
cls
call helloworld.exe
pause >nul
goto :1

@robert 2013-02-10 08:58:31

Before the end of your code, insert this line:

system("pause");

This will keep the console until you hit a key.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s;
    cout << "Please enter your first name followed by a newline\n";
    cin >> s;
    cout << "Hello, " << s << '\n';
    system("pause"); // <----------------------------------
    return 0; // This return statement isn't necessary
}

@PapaHotelPapa 2016-05-25 22:52:01

It also printed "Press any key to continue . . ." for me.

@JC203 2017-01-09 00:42:20

This worked for me over getchar()

@Izza 2010-05-31 10:49:08

You can even declare an integer at the beginning of your main() function (say int a;) and put std::cin >> a; just before the return value. So the program will keep running until you press a key and enter.

@Roman A. Taycher 2010-03-28 07:09:05

You could also stick

while(true)
    ;

or

for(;;)
    ;

at the end.

@Jesse Pepper 2012-03-14 06:28:05

Bad for the environment.

@Nathan 2013-03-29 18:38:57

-1 Busy spins are evil. They consume your CPU cycles and accomplish nothing. If you are going to do something like this, at least put a call to pause inside the loop body to yield the majority of your cycles.

@Thomas Matthews 2010-03-28 06:55:47

Add the following lines before any exit() function or before any returns in main():

std::cout << "Paused, press ENTER to continue." << std::endl;
cin.ignore(100000, "\n");

@Qwertie 2014-01-22 10:39:12

This does not work for me, the first line works but pressing enter does nothing

@Qwertie 2014-01-22 10:43:27

Changing this to cin.ignore(); works

@James McNellis 2010-03-27 14:31:35

Edit: As Charles Bailey rightly points out in a comment below, this won't work if there are characters buffered in stdin, and there's really no good way to work around that. If you're running with a debugger attached, John Dibling's suggested solution is probably the cleanest solution to your problem.

That said, I'll leave this here and maybe someone else will find it useful. I've used it a lot as a quick hack of sorts when writing tests during development.


At the end of your main function, you can call std::getchar();

This will get a single character from stdin, thus giving you the "press any key to continue" sort of behavior (if you actually want a "press any key" message, you'll have to print one yourself).

You need to #include <cstdio> for getchar.

@Billy ONeal 2010-03-27 14:39:36

This is probably the better of the two answers right now, but I would probably put a comment next to that to tell why you're actually doing it in real code. +1.

@Poni 2010-03-27 14:41:02

Another variant of this sort if to "#include <conio.h>" and use _getch().

@CB Bailey 2010-03-27 14:46:15

getchar does not solve the problem - or only in limited circumstances, at least. It reads a char from stdin, but if there are already characters buffered from stdin the program will carry on without waiting regardless of whether you print a prompt or not.

@James McNellis 2010-03-27 15:44:33

@Charles: A good point. Ignoring until \n is a partial solution, but won't help if more than one line of input is buffered. I do not know of a standard C++ way to clear everything from an input stream. :-/

@GManNickG 2010-10-03 10:35:29

@James: Old, but how about std::cin.ignore(std::cin.rdbuf()->in_avail());? Got it from here.

@James McNellis 2010-10-04 03:45:23

@GMan: I don't think that actually works: the streambuf probably isn't the only buffer between the input device and cin; the OS is probably doing other buffering in the background and there is no standard way to inspect that buffer.r

@GManNickG 2010-10-04 03:51:50

@James: while (std::cin.rdbuf()->in_avail()) std::cin.ignore(std::cin.rdbuf()->in_avail());? :S This should really be simpler.

@James McNellis 2010-10-04 05:13:28

@GMan: It depends on how buffering is handled by the system. One case where that solution will fail: the OS has its own buffer that is used when cin.rdbuf() is full. You check in_avail(); it's full and greater than zero so you call ignore(in_avail()) and clear the buffer; you check in_avail() again and it is now zero and you break out of the loop. But, meanwhile, you've typed stuff in and the OS hasn't started putting new characters into cin.rdbuf(). I think it's entirely dependent upon how the system buffers stdin; I'm not all that familiar with how modern systems do that.

@James McNellis 2010-10-04 05:14:21

[I do so little work with console input and output, I just don't know much about the details of this. And, if it were simpler, it would be C# :-P (I kid, I kid! Sort of...)]

@Xeo 2011-01-29 07:42:16

One option I use alot is std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); with #include <limits>.

@James McNellis 2011-01-29 07:43:07

@Xeo: That works unless there are multiple lines of data buffered in stdin.

@Xeo 2011-01-29 07:46:24

@James: Really? I always thought it ignores '\n' times std::numeric_limits<std::streamsize>::max()... Seems I still know little 'bout the standard library.

@James McNellis 2011-01-29 07:48:17

@Xeo: It ignores characters until it has read N characters (std::numeric_limits<std::streamsize>::max() in your example) or it reads the sentinel value ('\n'), whichever comes first.

@Xeo 2011-01-29 07:54:17

@James: You're right, but wouldn't a simple std::cin.ignore(std::numeric_limits<std::streamsize>::max()) be sufficient then? The default delimiter for ignore(...) is EOF. Of course it does not work if you have EOF in the stdin buffer, but usually that shouldn't happen? EDIT: Screw that, I just thought that over..

@James McNellis 2011-01-29 08:01:39

@Xeo: Once you reach EOF, there's nothing left to read :-)

@Lightness Races with Monica 2011-12-23 11:42:54

Please don't do this. :( It's not part of your program's function to do this.

@Furkat U. 2013-08-07 07:01:43

@nabulke is much easier in case you are using VS IDE, else system("pause"); is right answer

@Cheers and hth. - Alf 2018-01-07 09:38:39

Downvoted because adding stopping code is Very Bad Advice.

@Friendly advice 2012-09-17 00:24:04

All you have to do set a variable for x then just type this in before the return 0;

cout<<"\nPress any key and hit enter to end...";
cin>>x;

@tsx 2012-06-17 15:20:51

Call cin.get(); 2 times:

    //...
    cin.get();
    cin.get();
    return 0
}

@Madhawa Priyashantha 2015-06-14 13:54:04

but why twice ??

@QMaster 2015-06-16 14:33:00

what if we need another cin.get() for getting for example some string inside array before this? It's not work in this scenario.

@Northcode 2011-12-31 22:29:23

This seems to work well:

cin.clear();
cin.ignore(2);

If you clear the buffer first it won't be a problem when you read the next one. For some reason cin.ignore(1) does not work, it has to be 2.

@Konrad Rudolph 2011-12-31 22:35:07

2 is sometimes also not enough (when there are more key strokes queued). The correct way is to ignore as many characters as are in the queue. To with, cin.rdbuf()->in_avail. Not some magic number like 1 or 2.

@Bat_Programmer 2011-10-04 10:42:48

Just add the following at the end of your program. It will try to capture some form of user input thus it stops the console from closing automatically.

cin.get();

@Amos 2010-03-27 14:39:25

Why not just run the program from a console ie run the program from cmd.exe if you're using Windows. That way the window stays open after the program finishes.

[EDIT]: When I use KDevelop4 there is a fully fledged instance of Bash (a Linux CLI) running in a tab at the bottom of the IDE. Which is what I use in these sort of circumstances.

@Billy ONeal 2010-03-27 14:40:18

Because if you are using an IDE you don't generally use a console. You push go, the program runs, and that's it.

@S.Lott 2010-03-27 14:44:03

+1: Blindly using IDE isn't really all that helpful. Using a console to run console applications seems appropriate.

@anon 2010-03-27 14:49:03

Any competent IDE will keep the console on screen when the app terminates - Code::Blocks for example does exactly this.

@Billy ONeal 2010-03-27 15:04:01

@Neil Butterworth: Visual Studio does not, and I suspect that's what the OP is using. Though I agree with you that it should.

@S.Lott 2010-03-27 15:11:57

If VS can't be configured to keep the window open, then use the console itself.

@Hans Passant 2010-03-27 16:08:22

@Billy: VS does too, press Ctrl+F5. If you use Start Debugging (F5), it assumes you actually want to debug the program.

@James McNellis 2010-03-27 16:13:08

@nobugz: Unless I've screwed something up on my installation, which is quite possible, that is not the behavior in Visual Studio 2010 and I would have sworn that it's not the behavior of 2008. Is that a configurable option, do you know?

@Hans Passant 2010-03-27 17:11:37

@James: not that I'm aware of, I've never seen or heard it not work.

@James McNellis 2010-03-27 17:23:47

@nobugz: I figured it out. To get the window to stick around, you have to have /SUBSYSTEM:CONSOLE on the linker command line. The documentation says that this is the default if main is defined, but if I don't explicitly set it on the command line, VS kills the window when the application exits. sigh

@Hans Passant 2010-03-27 17:32:36

@James: that is required to get a console window in the first place. That in turn requires main() instead of WinMain(), not the other way around. I'm a bit lost...

@James McNellis 2010-03-27 17:55:50

@nobugz: If you start from an "Empty Project" instead of a "Win32 Console Application" the subsystem is not explicitly set in the project properties. If you define main in the project, the linker by default uses the CONSOLE subsystem. When debugging or running, you'll get a console window. However, unless you explicitly specify CONSOLE as the subsystem in the project properties, Visual Studio will not keep the console window open. I always start from an empty project and I rarely change individual project properties, so I've never seen the console window stick around. Sorry for the confusion

@Ben Voigt 2010-03-28 23:15:40

@James: If Visual Studio doesn't know you've got a console application, then Windows itself is allocating the console when the app starts, in which case it is also destroyed when the app exits.

@Matt Chambers 2011-09-13 18:16:54

James is right. I had the same problem with a "project from existing code" and setting the subsystem (which was blank) fixed it.

@John Dibling 2010-03-27 16:08:38

I usually just put a breakpoint on main()'s closing curly brace. When the end of the program is reached by whatever means the breakpoint will hit and you can ALT-Tab to the console window to view the output.

@Polaris878 2010-03-27 16:07:53

Okay I'm guessing you are on Windows using Visual Studio... why? Well because if you are on some sort of Linux OS then you'd probably be running it from the console.

Anyways, you can add crap to the end of your program like others are suggesting, or you can just hit CTRL + F5 (start without debugging) and Visual Studio will leave the console up once complete.

Another option if you want to run the Debug version and not add crap to your code is to open the console window (Start -> Run -> cmd) and navigate to your Debug output directory. Then, just enter the name of your executable and it will run your debug program in the console. You can then use Visual Studio's attach to process or something if you really want to.

Related Questions

Sponsored Content

16 Answered Questions

[SOLVED] How can I profile C++ code running on Linux?

  • 2008-12-17 20:29:24
  • Gabriel Isenberg
  • 489926 View
  • 1725 Score
  • 16 Answer
  • Tags:   c++ unix profiling

26 Answered Questions

[SOLVED] How can I get the application's path in a .NET console application?

8 Answered Questions

[SOLVED] Automatic exit from bash shell script on error

19 Answered Questions

10 Answered Questions

24 Answered Questions

[SOLVED] Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

4 Answered Questions

[SOLVED] How do I achieve the theoretical maximum of 4 FLOPs per cycle?

10 Answered Questions

3 Answered Questions

[SOLVED] C++ console application exiting immediately?

Sponsored Content