Simple C++ Question

Baseline

Member
Sep 24, 2001
183
0
0
I'm working on learning C++ by the book. Ofcourse the first programs you make are simple and command line based when they are run for the most part. I am in WinXP. After editing the code from the simple first program "Hello World", which we all know how simple that is in all languages, for some reason when I run it, it seems the box just pops up and closes immediately. Is there anything I can add in my source code to make the program stay open until the user decides to close it?

Thanks,
Dan
 

DAGTA

Diamond Member
Oct 9, 1999
8,172
1
0
Dan, declare a char ch; then at the end of your program, put in cin >> ch; This will cause the screen to stay open since the program will be waiting for you to input a character. Hit any key to end the program.

Also, you could run the program in a dos window and that would solve the problem as well.
Hope it helps.
-DAGTA
 

Baseline

Member
Sep 24, 2001
183
0
0


<< Dan, declare a char ch; then at the end of your program, put in cin >> ch; This will cause the screen to stay open since the program will be waiting for you to input a character. Hit any key to end the program. >>



By declare, you mean to create a new function like:

char ch()
{
}

int main()
{
blah blah blah;
blah blah;
cin >> ch;
return 0;
}

like that?

edit: even I think I know this looks wrong being my first few days into C++.. there would have to be something in that function I think.
 

Ameesh

Lifer
Apr 3, 2001
23,686
1
0


<<

<< Dan, declare a char ch; then at the end of your program, put in cin >> ch; This will cause the screen to stay open since the program will be waiting for you to input a character. Hit any key to end the program. >>



By declare, you mean to create a new function like:

char ch()
{
}

int main()
{
blah blah blah;
blah blah;
cin >> ch;
return 0;
}

like that?

edit: even I think I know this looks wrong being my first few days into C++.. there would have to be something in that function I think.
>>





not a function just a variable


so just write

char foo = 0;

cin >> foo;
 

HigherGround

Golden Member
Jan 9, 2000
1,827
0
0
i usually stick getchar() right before main returns ( this assumes you don't terminate anywhere in the code )

#include <stdio.h>
int main(void)
{
.
.
.

getchar( );
return 0;
}
 

PowerMacG5

Diamond Member
Apr 14, 2002
7,701
0
0
I usually type:

#include <iostream.h>
int main()
{
*
*
*
*
cin.get();
return 0;
}

if one cin.get() doesn't work i type:

#include <iostream.h>

int main()
{
*
*
*
*
cin.get();
cin.get();
return 0;
}

One of those should work depending on your compiler
 

Mje

Member
Jun 25, 2001
188
0
0
I usually use...
#include <conio.h>
int main() {
//code
_getch();
return 0;
}

They all basically do the same thing.... and that is... what you wanted. :)