0

I tried to program a calculator in C, but the program ignores my operator(plus, mins, etc.) which I try to scan out of the terminal.

Code following:

#include <stdio.h>
#include <stdlib.h>

int main() {
float Zahl1;
float Zahl2;
float Ergebnis;
char Methode ="";


printf("Geben Sie bitte eine Zahl ein.\n");
scanf("%f", &Zahl1);
printf("Geben Sie bitte eine zweite Zahl ein.\n");
scanf("%f", &Zahl2);
printf("Geben Sie ein Verechnungszeichen ein.");
scanf("%c", &Methode);


if (Methode == '+') 
   Ergebnis= Zahl1 + Zahl2;

else if(Methode == '-') 
    Ergebnis= Zahl1 - Zahl2;

else if(Methode == '*') 
    Ergebnis= Zahl1 * Zahl2;

else if(Methode == '/') 
    Ergebnis= Zahl1 / Zahl2;

printf("%f", Ergebnis);

return 0;

}

Terminal:

Geben Sie bitte eine Zahl ein.
5
Geben Sie bitte eine zweite Zahl ein.
7
Geben Sie ein Verechnungszeichen ein.-25905410257214286834448728064.000000%

Comment: I couldn't enter a operator and the number is appearing automatically.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
DavidCode
  • 9
  • 1
  • Use scanf(" %c", &c) ; & switch statement to check the character c if it's Division, multiplication, subtraction, addition instead of if else statements – MED LDN Dec 21 '20 at 10:53

1 Answers1

4

Problem: After the previous entries for operands, you press the ENTER key, which leaves a newline in the input buffer. Other format specifiers like %d, %f ignores leading whitespaces, but %c does not, and a whitespace (newline, for that matter) is a valid match and input.

Solution: You need to change

 scanf("%c", &Methode);

to

scanf(" %c", &Methode);
      ^^^

to avoid matching any existing leading whitespace already present in the input buffer being scanned and considered as the input.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261