Making Calculator say "error" when dividing by 0

Right, first of all after about 12 years of doing maths. I've just learnt that if you get an error on any calculator if you try to divide by 0 i.e 7/0.
So after trying to divide by 0 on my calculator, it crashes (which I found a bit amusing) Therefore I tried to add a bit of code that will give an error when dividing by 0, but it always crashes when I try to divide by 0 after trying multiple things.
Please help.
Here's the code:
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
#include <iostream>
using namespace std;

int main()
{
      int a;
      int b;
      int sum;
      string userResponse;
      char userinput;

      do{

      cout << "\t / = Divide, * = Multiply";
      cout << "\n\nEnter a calculation: ";
      cin >> a;
      cin >> userinput;
      cin >> b;


    switch(userinput)
    {
        case '+' : sum = a + b;
        break;
        case '-' : sum = a - b;
        break;
        case '*' : sum = a * b;
        break;
        case '/' : sum = a / b;


    }

    cout << "\nThe total of those numbers are: " << sum << endl;


    if(sum > 20){
      cout << "\nHa, your number is greater than 20 \n";
      }
       if(sum < 20){
       cout << "\nCan't catch me out, your number is less than 20 \n";
       }
       if(sum == 20){
       cout << "\nYour number is equal to 20 \n";
       }

       cout << "\nDo you want to use is again (Yes/No) \n";
       cin >> userResponse;

       }while(userResponse == "Yes");
}
It will always crash if you actually devise by zero (hardware interrupt). The trick would be to check if "b" is zero before you perform actual devision.
Topic archived. No new replies allowed.