Problem with initializing variables and cin

I keep getting this error: Uninitialized local variable 'input' used." I know what this means, but the problem is I want to cin a value.

If I initialize int input (e.g., int input = 0), then, when I enter Q to quit, the value "O" is outputted on the screen. I'm trying to get it so that users can only enter 1 and 2.

What do I need to change?

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
#include <iostream>
#include <cstdlib>
#include <string>
#include <cmath>

using namespace std;

int main()
{
	cout << "(1) Drop one chip; (2) Drop multiple chips; Enter 'Q' to quit: ";
	bool run = true;
	int input;
	while (run && input <= 2)
	{

		cin >> input;
		cout << input << endl;
		if (cin.fail()) { break; }


	}
	
	system("pause()");
	return 0;

}
12
13
int input;
while (run && input <= 2)

The problem is that the first time the loop is run, you try to compare input with 2 before input is actually initialized.

So either initialize it to 0 (or something less than or equal to 2) or change it to a do-while loop:
13
14
15
16
do
{
    // contents of loop here
} while (run && input <= 2);

Also, you don't need parentheses after the "pause" in your system call. (That's because you're not really calling a function -- you're executing a system command.)
In any case, you probably shouldn't be using system anyways: http://www.cplusplus.com/articles/j3wTURfi/
(For alternatives, see this: http://www.cplusplus.com/articles/iw6AC542/ )
Topic archived. No new replies allowed.