plz help problem about multiply and divide

i can add and subtract but cant multiplay and divide
plz help i can't figure out what's the problem

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
// Read data using cin repeatedly
#include<iostream>
using namespace std;

int main()
{

		// Variable declarations
		int num1, num2, sum;

		// Read input data repeatedly
		// Num: 8, Num2: 22
		while (cin >> num1 >> num2){
				// write your code here
				// here is an example
				// 8 + 22 = 30
				sum = num1 + num2;
				cout << "sum:" << sum << endl;
		}

		while (cin >> num1 >> num2){
				// write your code here
				// here is an example
				// 8 - 22 = -14
				sum = num1 - num2;
				cout << "sum" << sum << endl;
		}

		while (cin >> num1 >> num2){
				// write your code here
				// here is an example
				// 8 * 22 = 176
				sum = num1 * num2;
				cout << "sum" << num1 * num2 << endl;
		}

		while (cin >> num1 >> num2){
				// write your code here
				// here is an example
				// 8 / 22 = 0
				sum = num1 / num2;
				cout << "sum" << num1 / num2 << endl;
		}
		return 0; // indicate that program ended successfully
}	//	End function main
Question. How does this loop ever end?
 
while (cin >> num1 >> num2)

Answer. When the input operation fails and the cin.fail() flag is set.


Next question. Given that cin.fail() is true, how will any of the following loops ever execute at all?

After the closing brace at line 19, since none of the cin >> loops will run, control will continue eventually at line 44 and the program ends.


It might be better to use a single loop, and input an operator as well, one of + - * / .

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
#include<iostream>

using namespace std;

int main()
{
    cout << "Enter two integers and an operator + - * / \n";
    
    // Variable declarations
    int num1, num2;
    char op;

    // Read input data repeatedly
    while (cin >> num1 >> num2 >> op)
    {
        if (op == '+')
        {
            int sum = num1 + num2;
            cout << "sum:" << sum << endl;
        }
        
        // add additional if / else statements here.
     
     
        // repeat prompt message
        cout << "Enter two integers and an operator + - * / \n";     
    }

}
Topic archived. No new replies allowed.