Are if statements possible based off of a void?

I've searched this forum so I'm sorry if this has already been answered, but I'm just getting my feet wet with the Arduino Uno and C++ and right now I'm trying to create a basic calculator using the IDE Serial Monitor. My code so far is below. Everything works great, but if I use a "non-approved" operator (i.e. not +, -, *, /, or ^) it still prints the Serial.print(num1); Serial.print(calc); Serial.print(num2); Serial.print("="); Serial.println(result); after the default from the switch in the calculation.
Is there a way to insert an If statement, or something similar, into the loop so it wont print the calculation steps if the output of the switch is it's default?

float num1;
float num2;
char calc;
float result;

void setup() {
  Serial.begin(9600);
  Serial.println("What would you like to calculate?"); 
}

void loop() {
  while(Serial.available() > 0) {  
    num1 = Serial.parseFloat();
    calc = Serial.read();
    num2 = Serial.parseFloat();
    calculation();
    Serial.print(num1);
    Serial.print(calc);
    Serial.print(num2);
    Serial.print("=");
    Serial.println(result);
  }
}
 
void calculation() {
  switch (calc) {
    case '+' :
    result = num1 + num2;
    break; 
    case '-' : 
    result = num1 - num2; 
    break; 
    case '*' : 
    result = num1 * num2; 
    break; 
    case '/' : 
    result = num1 / num2; 
    break; 
    case '^' : 
    result = pow(num1, num2); 
    break; 
    default : 
    Serial.println("You did not enter +, -, *, /, or ^");
  }
}

case '^' :
result = pow(num1, num2);
default = false;
break;
default :
Serial.println("You did not enter +, -, *, /, or ^");
default=true;
}

if( !default )
{
then do the printing thing
}

What have you got the Line ending set to in the Serial monitor ?

Anything other than "No line ending" will result in extra characters after the one that you have entered. They will not match any of your cases so the default case will be executed

Try printing calc before the switch/case but print ">" immediately before it and "<" immediately after it so that you can see whether a non printing character is there

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.