Help with do while loops in c

When I run my program once it works just fine but when the loop starts over again, it skips the “Pick an operator” prompt and proceeds with the values. Need a solution for this please, I am bad with loops…

Here is the code:

#include <stdio.h>
#include <string.h>

int sum(int a, int b) {
      int c;
      c = a + b;
      return c;
    }

int difference(int a, int b) {
    int c;
    c = a - b;
    return c;
}

double product(double a, double b) {
    double c;
    c = a * b;
    return c;
}

double quotient(double a, double b) {
    double c;
    c = a / b;
    return c;
}

void invalid() {
    printf("Invalid Operator!");
}

int main() {
    
    int num1, num2;
    char operator;
     
    do { 
    printf("\nA. Add, B. Subtract, C. Multiply, D. Divide, Q. Quit"); 
    printf("\nPick an operator: ");
    scanf("%c", &operator);

    operator = toupper(operator);

    printf("Enter #1: ");
    scanf("%d", &num1);
    printf("Enter #2: ");
    scanf("%d", &num2);

    switch(operator) {
        case 'A': printf("Sum: %d", sum(num1, num2));
        break;
        case 'B': printf("Difference: %d",difference(num1, num2));
        break;
        case 'C': printf("Product: %.2f",product(num1, num2));
        break;
        case 'D': printf("Quotient: %.2f",quotient(num1, num2));
        break;
        default: invalid();
    }
    }while(operator != 'Q');
   
    return 0;
}

Hi @DavidLacsao, been a while since doing C, but as far as I remember scanf reads up to finding a newline char /n.
But with the second read you still have the previous “/n” in the buffer, so that became the second operatior.

I think you can just fix it by skipping any number or whitespace by formatting a space in scanf as

scanf(" %c", &operator);
// space before %c

And that should fix it.
Also you probably need the ctype.h file for toupper? Not 100% sure about this.

Hope this helps, :sparkles:

1 Like

@Marmiz thank you so much for the help. This actually worked. I will keep all your suggestions in mind :slight_smile: