okay, so we have solution. Why does it work?

Jul 24, 2018 at 12:27am
Here's my favorite solution to the pinned "Console closing down" issue. It uses what should be an infinite loop, but manages to only print each line once as opposed to infinitely. I'm not complaining, just curious. Why does this work?

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
29
30
31
32
33
34
35
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std; 
string response; 

int main() {

	// start loop 
	while (true)
	{

		cout << "what is your name?";
		cin >> response; 
		cout << "nice to meet you", response; cout << endl;
		cout << "how are you today?"; 
		cin >> response; 
		if (response=="bad")
		{
			cout << "I'm sorry to hear that"; 
			cout << endl; 
		}

		
        cout << " Ready to quit? Then enter 'y', or 'Y' "; 

		char c; 
		cin >> c; 

		if(c=='y'||c=='Y')
		{
			break;
		}
	}
}
Last edited on Jul 24, 2018 at 12:28am
Jul 24, 2018 at 3:23am
What do you think the variable 'c' contains when the program encounters the if() statement?

Do you know what a "break" statement does?

You may want to run the program with your debugger, set a breakpoint early in main() and single step through the rest of the program. Make sure you watch the value of the various variables as you step.


Jul 24, 2018 at 6:07pm
The pinned "Console closing down" issue is completely different, and, to be honest, should be unpinned. That thread contains workarounds for the "problem" of CLI applications working correctly after execution through an IDE in debug mode. Release builds can also be 'hosted' by the IDE in this way, but gain very little over actually executing from the build directory.

What you're doing is creating an infinite loop around a whole block of logic that will continually repeat until the user is sick of it. This is not a simple one-time prompt at the end that asks for a single character press. The workarounds in that thread ask for a character press, and no matter what the user enters, the program will exit.

Breakpoint on the closing brace in main() if all you need is a moment to examine some output output. Don't fill your code with needless getchars/pauses/cins/"press a key to continue"s...
Last edited on Jul 24, 2018 at 6:10pm
Topic archived. No new replies allowed.