Bool function loop

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
bool isInt (int& a)
{
	try
	{
		 if (!(cin >> a))
		 {
			 throw a;
			 return true;
		 }
	}
	catch(int r)
	{
		 cout << "Invalid numeric number";
		 cin.clear();
		 cin.ignore( cin.rdbuf()->in_avail() );
		 return false;
	}
return true;
}

void Complex::getData()
{
	//check for valid numeric number

		cout << "Enter Real: ";
		cin >> this->real;
		while (!isInt(this->real))
		{
			cout << "Please enter a numeric number (0-9)";
			cin >> this->real;
			cin.clear();
			cin.ignore( cin.rdbuf()->in_avail() );
		}


	try
	{
		cout << "Type of operation to perform (+, -, *, /) ";
		cin >> this->opt;
		if(opt != '+' && opt != '-' && opt != '*' && opt != '/')
		{
			throw opt;
		}
	}
	catch (char n)
	{
		cout << "Operation Error: " << n << " is an invalid operator\n";
		while(opt != '+' && opt != '-' && opt != '*' && opt != '/')
		{
			cout << "Please enter a valid operator (+, -, *, /) ";
			cin >> this->opt;
			cin.clear();
			cin.ignore( cin.rdbuf()->in_avail() );
		}
	}

}


Basically I would like to ensure that a valid numeric number is being input.
Now If I were to input a valid number, the program will hang.
If I were to input a invalid number, the program will go into a crazy loop.

umeric number (0-9)Invalid numeric numberPlease enter a numeric number (0-9)Inva
lid numeric numberPlease enter a numeric number (0-9)Invalid numeric numberPleas
First, awful use of exceptions. If you are going to handle the error just below, use an if...else structure.
Line 8 will never be executed (and it shouldn't return true)
You are trying to read the data twice (when you call your function and inside the while)
cin.rdbuf()->in_avail() This is returning 0.
Topic archived. No new replies allowed.