while loop with a bool and getline(cin, x).

I wanted to make a program that I could use as a console. I have created a while loop as you can see below (code1). i know i can fix this by putting getline after while but why does this not work? and why does else repeat when i switch their spots(code2).


code1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
using namespace std;

int main() {

	string line;
	bool exit = false;
	while (getline(cin, line)||exit == false)
	{


		if (line == "help" || line == "?")
			cout << "Command1";
		else if (line == "doA")
			cout << "option 1";
		else if (line == "doB")
			cout << "option 2";
		else if (line == "exit")
			exit = true;
		else cout << "Invalid Command" << endl;
	}

}


code2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
using namespace std;

int main() {

	string line;
	bool exit = false;
	while (exit == false || getline(cin, line))
	{


		if (line == "help" || line == "?")
			cout << "Command1";
		else if (line == "doA")
			cout << "option 1";
		else if (line == "doB")
			cout << "option 2";
		else if (line == "exit")
			exit = true;
		else cout << "Invalid Command" << endl;
	}

}
Your 'while' statement has two conditions, separated by an 'OR'.

It tries to evaluate the first condition; if necessary - and only if necessary - it will then evaluate the second.

In code1, the first condition actually requires it to 'get a line': so it will sit there waiting until you feed it (bit like my cat!). Once you have put in anything it will deal with it according to the block of statements.

In code2, the first condition will immediately evaluate as 'true' (because you have already assigned exit as false!), so it doesn't need to do the second condition (because OR will be satisfied), so it attempts to do the commands in the while block. Since you haven't actually defined line (because it didn't need to look at the second condition) it will go to the last else and say "Invalid command".
Last edited on
You might want to have a look at:
http://stackoverflow.com/questions/1799072/c-short-circuiting-of-booleans

while (exit == false && getline(cin, line))
Last edited on
Topic archived. No new replies allowed.