C++ School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a C++ Expert!

Join 307,136 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,916 people online right now. Registration is fast and FREE... Join Now!




Holding The Execution Window Open

5 Pages V  1 2 3 > »   

Holding The Execution Window Open, Title 2: How do I pause for input?

Amadeus

18 Jul, 2007 - 05:02 PM
Post #1

g+ + -o drink whiskey.cpp
Group Icon

Joined: 12 Jul, 2002
Posts: 13,284



Thanked: 149 times
Dream Kudos: 25
My Contributions
First and foremost, allow me to assure you that this post is not meant to discuss the sleep() command, mutexes or semaphores, or using threads. It is meant to address one of the most commonly asked questions by newcomers to C++, especially those who use an IDE for programming.

When my program runs, the execution window closes immediately. What is wrong? How do I hold it open/pause it?

Nothing is wrong - that is exactly what your program has been designed to do - execute, then exit.

When newcomers ask the question above, they are almost always told to use one of the following commands:
CODE

getch();
//or
system("pause");


Both of the commands above are platform specific solutions, and do not conform to ANSI standards. They use components that are found on certain architectures, but not others. It is preferable to use a solution that does conform to standards, and uses accepted C++ methods.

One such method that is also often recommended is using:
CODE

cin.get();

This solution will indeed pause for user input - as long as no characters are currently in the stream. As most applications will have asked for input several times, it is likely that there will be at least one character in the stream (often a newline) that will be captured by the cin.get() method, and the application will continue on past.

There are many ways to do it and remain standards compliant. I will not reinvent the wheel, but will simply post one example already submitted by a member of this site - Xing (hope you don't mind me posting this).

This simple snippet is as follows:
CODE

#include <iostream>
#include <limits>

int main() {
  
  // Rest of the code    
  
  //Clean the stream and ask for input
  std::cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
  std::cin.get();
  return 0;
}

The original submission can be found here:

http://www.dreamincode.net/code/snippet582.htm

This method is standards compliant, and will hold the command window open without invoking any executables that may or may not be present.

Of course, you can always run the program from the command line. smile.gif

User is offlineProfile CardPM
+Quote Post


no2pencil

RE: Holding The Execution Window Open

18 Jul, 2007 - 06:09 PM
Post #2

i R L33t Skiddie, k?
Group Icon

Joined: 10 May, 2007
Posts: 13,494



Thanked: 303 times
Dream Kudos: 2875
Expert In: Goofing Off

My Contributions
QUOTE

Of course, you can always run the program from the command line.

Yeah, if someone refuses to use getc (cin) or sleep, then just run it from the command line... otherwise code a windows interface.

What would be an example of a program that can not use getc (cin) or sleep?

How about if you did something like the following:

CODE

#include <stdio.h>

int main(void) {
  int i=0,k=0,j=999999;
  printf("Our Program is running...\n");
  for(;i<j;i++) {
    if(i==j)return 0;
    else {
        printf(" ");
        printf("\b");
    }
  }
}


User is online!Profile CardPM
+Quote Post

Topher84

RE: Holding The Execution Window Open

19 Jul, 2007 - 07:06 AM
Post #3

D.I.C Regular
Group Icon

Joined: 4 Jun, 2007
Posts: 258



Thanked: 3 times
Dream Kudos: 25
My Contributions
may want to include that getch() is part of the #include <conio.h> for c++ otherwise you get a compile error

CODE

#include <iostream>
#include <string>
#include <conio.h> //for getch()

using namespace std;

void main()
{
   string strInput;

   cout << "Enter Some Stuff Here: "; //Prompt for input
   cin   >> strInput;                          //Get Input

   cout << strInput;                          //Display Input

   getch();                                       //Pause
}//end main


This post has been edited by Topher84: 19 Jul, 2007 - 07:09 AM
User is offlineProfile CardPM
+Quote Post

Amadeus

RE: Holding The Execution Window Open

19 Jul, 2007 - 08:50 AM
Post #4

g+ + -o drink whiskey.cpp
Group Icon

Joined: 12 Jul, 2002
Posts: 13,284



Thanked: 149 times
Dream Kudos: 25
My Contributions
I think my point may have been missed. I advise against the use of getch(). It is a platform dependent function that does not comply to ANSI standards. It is not part of standard C++.
User is offlineProfile CardPM
+Quote Post

no2pencil

RE: Holding The Execution Window Open

19 Jul, 2007 - 08:52 AM
Post #5

i R L33t Skiddie, k?
Group Icon

Joined: 10 May, 2007
Posts: 13,494



Thanked: 303 times
Dream Kudos: 2875
Expert In: Goofing Off

My Contributions
QUOTE(Amadeus @ 19 Jul, 2007 - 09:50 AM) *

I think my point may have been missed. I advise against the use of getch(). It is a platform dependent function that does not comply to ANSI standards.

I got your point. There is no conio.h on *nix systems, so the code is not portable.
User is online!Profile CardPM
+Quote Post

Topher84

RE: Holding The Execution Window Open

19 Jul, 2007 - 09:28 AM
Post #6

D.I.C Regular
Group Icon

Joined: 4 Jun, 2007
Posts: 258



Thanked: 3 times
Dream Kudos: 25
My Contributions
QUOTE(no2pencil @ 19 Jul, 2007 - 09:52 AM) *

QUOTE(Amadeus @ 19 Jul, 2007 - 09:50 AM) *

I think my point may have been missed. I advise against the use of getch(). It is a platform dependent function that does not comply to ANSI standards.

I got your point. There is no conio.h on *nix systems, so the code is not portable.


my bad... i've just always used getch() just because of the easy use and the most we programmed in college were win32 console (as i'd say most people looking for help here are doing also) apps hence no need to include *nix systems. Nice write-up though!

User is offlineProfile CardPM
+Quote Post

raedbenz

RE: Holding The Execution Window Open

22 Jul, 2007 - 12:04 AM
Post #7

New D.I.C Head
*

Joined: 13 Dec, 2006
Posts: 20


My Contributions
hi..if u use VC++ express edition , simply use Start without DEBUGGING ( Ctrl + F5)..

User is offlineProfile CardPM
+Quote Post

sh0elace

RE: Holding The Execution Window Open

6 Aug, 2007 - 09:29 PM
Post #8

D.I.C Head
Group Icon

Joined: 5 Aug, 2007
Posts: 225


Dream Kudos: 25
My Contributions
How would one do so while working in C, not C++?
User is offlineProfile CardPM
+Quote Post

Xing

RE: Holding The Execution Window Open

6 Aug, 2007 - 09:59 PM
Post #9

D.I.C Addict
Group Icon

Joined: 22 Jul, 2006
Posts: 723



Thanked: 15 times
Dream Kudos: 1575
My Contributions
Snippet shown by me would not work in case of numeric input failures since ignore does not clear the fail state of input stream.. More complete solution could be something like:

CODE
#include <iostream>
#include <limits>

void waitForInput()
{
    std::cout <<"Press Enter to exit"<<std::endl;
    if (!std::cin)
    {
        std::cin.clear();// clear the fail flag since ignore does not do that.
    }
    //Clean the stream and ask for input
    std::cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
    std::cin.get();
}
int main()
{

    // Rest of the code

    waitForInput();

}


This post has been edited by Xing: 6 Aug, 2007 - 10:15 PM
User is offlineProfile CardPM
+Quote Post

Xing

RE: Holding The Execution Window Open

6 Aug, 2007 - 10:24 PM
Post #10

D.I.C Addict
Group Icon

Joined: 22 Jul, 2006
Posts: 723



Thanked: 15 times
Dream Kudos: 1575
My Contributions
QUOTE(sh0elace @ 7 Aug, 2007 - 10:59 AM) *

How would one do so while working in C, not C++?

You can wait for user to hit enter using this
CODE

printf("Hit 'ENTER' to exit"\n");
fflush(stdout);
(void)getchar();


This post has been edited by Xing: 6 Aug, 2007 - 10:25 PM
User is offlineProfile CardPM
+Quote Post

sh0elace

RE: Holding The Execution Window Open

7 Aug, 2007 - 08:11 AM
Post #11

D.I.C Head
Group Icon

Joined: 5 Aug, 2007
Posts: 225


Dream Kudos: 25
My Contributions
QUOTE(Xing @ 7 Aug, 2007 - 01:24 AM) *

QUOTE(sh0elace @ 7 Aug, 2007 - 10:59 AM) *

How would one do so while working in C, not C++?

You can wait for user to hit enter using this
CODE

printf("Hit 'ENTER' to exit"\n");
fflush(stdout);
(void)getchar();



Ahh, thank you thank you! You just helped me out a bunch.
User is offlineProfile CardPM
+Quote Post

ajaymatrix

RE: Holding The Execution Window Open

14 Aug, 2007 - 11:10 AM
Post #12

D.I.C Regular
Group Icon

Joined: 15 May, 2007
Posts: 409



Thanked: 1 times
Dream Kudos: 100
My Contributions
that cleared a lot of my doubts..
good article...
User is offlineProfile CardPM
+Quote Post

xtreampb

RE: Holding The Execution Window Open

4 Oct, 2007 - 07:08 AM
Post #13

D.I.C Head
**

Joined: 20 Jun, 2007
Posts: 165



Thanked: 4 times
My Contributions
I learned to create a batch file using notepad (when using windows OS)

if the name of my program was "Game_Over" i would type

CODE

Game_Over.exe
pause


and i would just execute the batch file. but the only problem is that the name of the exe. file has to be one word.
User is offlineProfile CardPM
+Quote Post

Smarf

RE: Holding The Execution Window Open

12 Oct, 2007 - 03:54 AM
Post #14

D.I.C Head
**

Joined: 21 Sep, 2007
Posts: 80



Thanked: 4 times
My Contributions
QUOTE(raedbenz @ 22 Jul, 2007 - 01:04 AM) *

hi..if u use VC++ express edition , simply use Start without DEBUGGING ( Ctrl + F5)..


I tried to bring this point up with someone in my class but not even my teacher understood what I was trying to say.

If you make the program for someone other than yourself, they aren't going to open up your code in an IDE (like Visual XX Express Edition) to run it. They're going to use the little exe file that comes with it like they do for all their other programs. So Ctrl + F5 doesn't work.
User is offlineProfile CardPM
+Quote Post

NickDMax

RE: Holding The Execution Window Open

14 Oct, 2007 - 06:57 AM
Post #15

Can grep dead trees!
Group Icon

Joined: 18 Feb, 2007
Posts: 5,267



Thanked: 293 times
Dream Kudos: 1175
Expert In: Java/C++

My Contributions
...yes but the truth is, as a user, it is really IRRITATING to have to press a key when a program finishes. One of the really nice things about a command line program is they you can put them into a batch file. Then you can use piping to take the output of one program and insert in as the input to another. This becomes problematic if user interaction is needed.

The idea of holding the execution window open is great for assignments, and ok in some programs, but not great for utility programs that a real user may use.
User is offlineProfile CardPM
+Quote Post

Lt_Kernel

RE: Holding The Execution Window Open

21 Oct, 2007 - 01:33 PM
Post #16

New D.I.C Head
*

Joined: 5 Sep, 2007
Posts: 48


My Contributions
it closes when it goes to the third line
first line hitting return ok
second hitting return it closes

and no2pencil no cin
same as read only?

is there no other way that wont close
even hitting return until you die?

User is offlineProfile CardPM
+Quote Post

Jingle

RE: Holding The Execution Window Open

17 Dec, 2007 - 03:24 PM
Post #17

D.I.C Regular
***

Joined: 20 Oct, 2007
Posts: 261


My Contributions
if using c can you just us getchar()?
as long as the buffer is clear anyway?
User is offlineProfile CardPM
+Quote Post

draike

RE: Holding The Execution Window Open

2 Feb, 2008 - 11:14 PM
Post #18

New D.I.C Head
*

Joined: 2 Feb, 2008
Posts: 4


My Contributions
ok i hope people are still reading this and putting in there input cause i myself am a student and would like new , interesting and just plain standard ways of using C++

http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=01
will be the source of the base of this code...

if you are not using <windows.h> just ignore this post
/* PSUEDO */
add a bool array of 256;
add a MSG;
send to registered WNDPROC
determine wether they key is acceptable or not for exiting or any
other command
and if so exit...

exa:CODE
/* global if you want */
bool keys[256];
/* WINMAIN - just for kicks */
bool exit;
MSG msg; // no further handling needed
/* where you want input without continuing */
while (!exit)
{
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
// do whatever from send to WNDPROC to asserting the keys here
}
// if you send to WNDPROC(HWND,MSG,HWORD,LWORD) make sure that
// you test when finished ^note there is not bool* so thats why global
// to make sure that exit can be true by
if ( keys[VALUE_FOR_EXIT] ) exit=true;
}

This post has been edited by draike: 2 Feb, 2008 - 11:18 PM
User is offlineProfile CardPM
+Quote Post

P4L

RE: Holding The Execution Window Open

14 Feb, 2008 - 07:15 AM
Post #19

Geek 4 Life
Group Icon

Joined: 7 Feb, 2008
Posts: 2,178



Thanked: 16 times
Dream Kudos: 125
My Contributions
This has definitely helped me out since my school teaches programming concepts in C
User is offlineProfile CardPM
+Quote Post

Sepanto

RE: Holding The Execution Window Open

22 Mar, 2008 - 03:28 AM
Post #20

D.I.C Head
Group Icon

Joined: 20 Mar, 2008
Posts: 97


Dream Kudos: 50
My Contributions
I generally (when testing my program) just do
CODE

int main()
{
char garbage;
{
body
}
cin<<garbage;
return 0;
}


This post has been edited by Sepanto: 22 Mar, 2008 - 03:29 AM
User is offlineProfile CardPM
+Quote Post

5 Pages V  1 2 3 > » 
Reply to this topicStart new topic

Time is now: 11/21/09 02:59PM

Live C++ Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month