MisterGeeky
MisterGeeky

Reputation: 254

Crazy Calculator

The following is an edited code snippet from one of my larger programs.
(Original code can be found here)

I've made into a run-able program (It has errors)

#include<iostream>
#include<math.h>
using namespace std;
int main(){
    char op;
    double n1,n2;
    while(true){
        cin>> n1 >> op >> n2;
        switch(op){
            case '+' : cout<<n1 + n2 ; break;
            case '-' : cout<< n1 - n2 ; break;
            case 'x' :
            case '*' : cout<< n1 * n2 ; break;
            case '/' : cout<< n1/n2 ; break;
            case '^' : cout<< pow(n1,n2); break;
            case '<' : (n1<n2)? cout<<"True":cout<<"False"; break;
            case '>' : (n1>n2)? cout<<"True":cout<<"False"; break;
            case '=' : (n1==n2)? cout<<"True":cout<<"False"; break;
            case '%': int N1 = floor(n1); int N2 = floor(n2); cout << N1 % N2; break;
            default : cout<< "That operation is not available";
        }
    }
}

Note : I am using Code::Blocks running on Windows Vista.

There are two issues that I am encountering with the code.

Why are these things happening?

Upvotes: 0

Views: 276

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254631

I am unable to put the % part as a case in the switch-case. My compiler is throwing an error when I do this.

You forgot to show us what you tried, and what the error was, but I guess you tried to declare and initialise some variables within the switch block:

switch(op){
    //...
    case '%': int N1 = floor(n1); int N2 = floor(n2); cout << N1 % N2; break;
    //...
}

That's not allowed, to prevent the program from jumping into the variables' scope without initialising them. Instead, you'll need to introduce an inner block to scope the variables within that case:

case '%': {int N1 = floor(n1); int N2 = floor(n2); cout << N1 % N2; break;}
          ^                                                               ^

or don't bother with the variables at all:

case '%': cout << floor(n1) % floor(n2); break;

When I enter a gibberish value (string) for the input, the program goes into an infinite loop.

That's because you're not checking the result of the input. The simplest fix is to end the loop when input fails:

while (cin>> n1 >> op >> n2) {
    switch (op) {
        //...
    }
}

Alternatively, you could check the result in the loop, clearing the error (with cin.clear()) if it fails.

Upvotes: 4

Alexander L. Belikoff
Alexander L. Belikoff

Reputation: 5721

  • Not sure why % causes issues: can you show the error code? Sounds like a typo to me
  • You must check the success of input/conversion operations. When it fails, you never break out of the loop, since your op code is gibberish and you hit the default case.

Upvotes: 0

Related Questions