0

Im making a C calculator using switch case. It has a endless while loop b ut after the first loop it stops working? Here is my code:

#include <stdio.h>

int main() {
    char opr;
    double x, y;
    int i = 1;

    while (i < 2) {
        printf("\nPick an operator (+, -, *, /): ");
        scanf("%c", &opr);
        getchar();
        printf("\nPick 2 numbers ");
        scanf("%lf %lf", &x, &y);

        switch (opr) {
            case '+':
                printf("\n%.1lf + %.1lf = %.1lf\n", x, y, x + y);
                break;

            case '-':
                printf("\n%.1lf - %.1lf = %.1lf\n", x, y, x - y);
                break;

            case '*':
                printf("\n%.1lf * %.1lf = %.1lf\n", x, y, x * y);
                break;

            case '/':
                if (y == 0) {
                    printf("\nY can't be 0. Choose a new value: ");
                    scanf("%lf", &y);
                }
                printf("\n%.1lf / %.1lf = %.1lf\n", x, y, x / y);
                break;

            default:
                printf("\nPick a valid operator.\n");
        }
        printf("\n***************************************************\n");
    }
}

After the first loop it says "Pick a valid operator" even when i do. Help appreciated because im a newbie.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • 4
    `scanf(" %c", &opr);` maybe. – 001 Mar 01 '22 at 18:54
  • That was a simple fix. Thanks – Ilya Lantukhov Mar 01 '22 at 18:56
  • 1
    Does this answer your question? [scanf("%c") call seems to be skipped](https://stackoverflow.com/questions/29775323/scanfc-call-seems-to-be-skipped) – 001 Mar 01 '22 at 18:57
  • 1
    Also, I don't think the `getchar();` is needed since `scanf("%lf %lf", &x, &y);` will skip leading spaces. – 001 Mar 01 '22 at 18:59
  • 1
    That's right: it's the `%c` that doesn't skip leading whitespace unless told to. – Weather Vane Mar 01 '22 at 19:06
  • Ilya Lantukhov, Tip: rather than only print an error message, print useful information as to the problem and remedy: `printf("\nASCII code %d not a valid operator\nPick a valid operator +-/*\n", opr);`. You may have found the problem yourself then. – chux - Reinstate Monica Mar 01 '22 at 19:20
  • What makes Johnny's solution valid is when you type something and then press enter key your buffer is filled by a character sequence and the \n or \r depending on the os. But you are trying to read the strings "only". So your program's stdin buffer has \n or \r waiting to be flushed. – Ali Berat Çetin Mar 01 '22 at 22:10

0 Answers0