Hello World! And the console stays open. No fuss!

Took "Hello World" and used a simple loop to force the console open. thnx @manga for the advice!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

#include <iostream>
using namespace std;
int main() {
	while (true)

	{
		cout << "Hello world!";
		cout << endl;
		cout << "would you like to exit?"; cout << endl;

		cout << "please enter 'Y'";

		char c;
		cin >> c;
		if (c == 'y' || c == 'Y')
		{
			break;
		}
	
	}

	
	
}


  
Last edited on
or...

in debug mode, put a breakpoint at line 25 (or wherever your closing brace for main() is)

in release mode, navigate to the release directory, open a console at that directory (e.g. Windows, with Explorer, you can type "cmd" right in the address bar), and type out its name to run it
Hello Willogical,

Have a look at http://www.cplusplus.com/forum/beginner/1988/ This has several examples of how to keep the console open.

Quite often i put this code just before the return in main:
1
2
3
4
// The next line may not be needid. If you have to press enter to see the prompt it is not needed.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
std::cout << "\n\n Press Enter to continue";
std::cin.get();


Sometimes I will include the header file "<conio.h>", which is not a standard C++ header file and not always to everyone, but it does allow me to use "_getch()" to press any key. Not recommended for finished code, but nice to put a pause in your program while writing it without using "system("pause");" which is bad.

Hope that helps,

Andy
Last edited on
<conio.h> is probably worse than system("pause"), I'd say.
start->cmd

c:\folder\programname

you are welcome.

Ah, the blissful joy of a program that runs as expected.

Well just remember...

For every problem there is a nice simple solution that doesn't work.
<conio.h> is probably worse than system("pause"), I'd say.


IMHO, if you're writing a console program that uses either of them, you're probably doing something wrong.

Don't get me wrong, if it's there to make your workflow easier it's totally fine - and who cares how you pause, but in the wild, the vast majority of console programs should never even prompt the user, much less require the user to press a key to continue. Non-interactivity and scriptability is the core strength of the command line. If you're printing irrelevant output or worse requiring someone to sit at the terminal, you're actively making your program harder to use.

Beats me why this is never taught. It's pretty fundamental, IMO.
Last edited on
mbozzi: Agreed. Although I will add that TUIs are legit, if properly implemented. Of course, the majority of console programs that require a keypress at the end are not proper TUIs.
Topic archived. No new replies allowed.