Dec 30, 2022 at 2:31am Dec 30, 2022 at 2:31am UTC
Note that
std::istream::operator >>(int & val)
does
not simply read a
single digit or character. It reads a
sequence of characters (which usually ends when the user hits
enter ). The char sequence as a whole will then be converted into an
int
value.
https://cplusplus.com/reference/istream/istream/operator%3E%3E/
Note: You might want to look into
std::istream::get(char & c)
for reading a single character.
Last edited on Dec 30, 2022 at 2:37am Dec 30, 2022 at 2:37am UTC
Dec 30, 2022 at 9:57am Dec 30, 2022 at 9:57am UTC
Why have "Calculate again" at the end of every case? Why not have after the switch? Also, there's no error output if an invalid operator is entered.
while (!(cin >> op) || (op < 1 || op > 4)){
Also, there's no check for division by 0 - which will cause a run-time error.
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 58 59 60 61 62
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout << "Calculator 2.0\n\n" ;
for (char again = 'Y' ; again == 'y' || again == 'Y' ; ) {
double x, y, ans;
int op;
cout << "1. Addition\n" ;
cout << "2. Substraction\n" ;
cout << "3. Multiplication\n" ;
cout << "4. Division\n" ;
cout << "Enter an operation (1 - 4): " ;
while (!(cin >> op) || (op < 1 || op > 4)) {
cout << "Only choose above choices: " ;
cin.clear();
cin.ignore(100, '\n' );
}
cout << "Enter two digits: " ;
while (!(cin >> x >> y)) {
cout << "Must be 2 numbers: " ;
cin.clear();
cin.ignore(100, '\n' );
}
switch (op) {
case 1:
ans = x + y;
cout << x << " + " << y;
break ;
case 2:
ans = x - y;
cout << x << " - " << y;
break ;
case 3:
ans = x * y;
cout << x << " * " << y;
break ;
case 4:
if (y != 0) {
ans = x / y;
cout << x << " / " << y;
} else {
ans = NAN;
cout << "Attempted division by 0" ;
}
break ;
}
cout << " = " << ans << '\n' ;
cout << "Calculate again [Y/N]: " ;
cin >> again;
}
}
Last edited on Dec 30, 2022 at 10:59am Dec 30, 2022 at 10:59am UTC