About getting input

There are 2 codes that I want to know the difference between them.
I still cannot understand if swapping the getting input command is going
to affect the code or not.

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

using namespace std;

int main(){
    char ch;
    do{
        int a,b,c;
    
        cin >> ch;
        if(ch == '+'){
            cin >> a >> b;
            c = a + b;
            cout << c << endl;
        }else if(ch == '-'){
            cin >> a >> b;
            c = a - b;
            cout << c << endl;
        }else if(ch == '*'){
            cin >> a >> b;
            c = a * b;
            cout << c << endl;
        }else if(ch == '/'){
            cin >> a >> b;
            c = a / b;
            cout << c << endl;
        }else if(ch == '%'){
            cin >> a >> b;
            c = a % b;
            cout << c << endl;
        }else{
            cout << "Invalid operation. Try again." << endl;
        }
    }while(ch != 'x' && ch != 'X');
}
#include<iostream>

using namespace std;

int main(){
    char ch;
    cin >> ch;
    do{
        int a,b,c;
    
        if(ch == '+'){
            cin >> a >> b;
            c = a + b;
            cout << c << endl;
        }else if(ch == '-'){
            cin >> a >> b;
            c = a - b;
            cout << c << endl;
        }else if(ch == '*'){
            cin >> a >> b;
            c = a * b;
            cout << c << endl;
        }else if(ch == '/'){
            cin >> a >> b;
            c = a / b;
            cout << c << endl;
        }else if(ch == '%'){
            cin >> a >> b;
            c = a % b;
            cout << c << endl;
        }else{
            cout << "Invalid operation. Try again." << endl;
        }
        cin >> ch;
    }while(ch != 'x' && ch != 'X');
}
Last edited on
Yes, there is a subtle difference in behavior.

Lets say the user inputs the following:
+ 3 4 x


On the first program, the user enters 'x' at cin >> ch, and then it will do the else statement (lines 31-33), and print Invalid operation.

On the second program, the user enters 'x' at cin >> ch, and it will check the while loop condition before looping again, and so the loop will end before "Invalid operation" is ever printed.

First program:
+ 3 4 x
7
Invalid operation. Try again.


Second program:
+ 3 4 x
7
Last edited on
Topic archived. No new replies allowed.