Press any Key or Enter to Continue or Press N to stop Problem

Hello. I have a concern in the code below. The program should continue whatever keys I entered or whenever I press the Enter key and the character 'N' should end the program. But whenever I Press N, which should terminate the program still continues to loop. What seems to be the problem here?


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
#include <iostream>
using namespace std;

int main() {
    char oper;
    char stop; //stop the program
    float num1, num2;
    while (stop != 'N') {
    cout << "Enter an operator (+, -, *, /): ";
    cin >> oper;
    cout << "Enter two numbers: " << endl;
    cin >> num1 >> num2;

    switch (oper) {
        case '+':
            cout << num1 << " + " << num2 << " = " << num1 + num2;
            break;
        case '-':
            cout << num1 << " - " << num2 << " = " << num1 - num2;
            break;
        case '*':
            cout << num1 << " * " << num2 << " = " << num1 * num2;
            break;
        case '/':
            cout << num1 << " / " << num2 << " = " << num1 / num2;
            break;
        default:
            
            cout << "Error! The operator is not correct";
            break;
    }cout << "\nPress any Key or Enter to Continue or Press N to stop" << endl;
     cin.get();
     cin.clear ();
     cin.ignore();
     
    } 

    return 0;
}
Last edited on
In function 'int main()':
8:5: warning: 'stop' is used uninitialized in this function [-Wuninitialized]

Nor do you ever read any input into stop.
1) stop isn't initialised on L6. It should be initialised to a value other than 'N'. All variables should be initialised when defined.

2) L32 You are obtaining a char - but then throwing it away. Shouldn't L32 be

 
cin.get(stop);

Last edited on
The implicit tip here is that you should enable compiler warnings.

Search "[your compiler] enable warnings".
Topic archived. No new replies allowed.