0
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNING
#endif

#include <stdio.h> // basic I/O printf
#include <stdlib.h> // malloc, calloc, realloc
#include <string.h> // strcpy
#include <time.h>

/*Arithmatic practice*/

int main() {
    /*Variable declaration*/    
    char o;
    char c;
    int a, b;

    while (1) {

        printf("Enter values a, operator and b\n");
        scanf("%d %c %d", &a, &o, &b);
        
        if (o == '+') {
            printf("%d %c %d = %d \n", a, o, b, a + b);
        }
        else if (o == '*') {
            printf("%d %c %d = %d \n", a, o, b, a * b);
        }
        else if (o == '/') {
            printf("%d %c %d = %f \n", a, o, b, a / b);
        }
        else if (o == '-') {
            printf("%d %c %d = %d \n", a, o, b, a - b);
        }
        else{
            printf("Invalid Input \n");
        }
        
        printf("Do you want to exit Y/N \n");
        scanf("%c", &o); // this part does not execute

        if (o == 'N' || o == 'n') {
            continue;
        }
        else if (o == 'Y' || o == 'y') {
            break;
        }
        else{
            printf("Invalid Input \n");
        }
    }
        printf("successfully exited");
        return 0;
}

when I run this code, the below scanf function is ignored and is not executed. Could someone help me out to figure out this? I honestly have no idea why this code is not working.

scanf("%c", &o) //ignored and not executed;

My assumption is overwriting o has something to do with this but not really sure why this code is not working because this is supposed to be an example code and I saw this code was working on a video.

Is it possible that exactly the same code is not working on a different IDE?

  • Thanks now it works. Could you tell me whats the difference? – True Roughly Nov 13 '20 at 20:04
  • Change `scanf("%c", &o);` to `scanf(" %c", &o);` NOTE the additional space. `"%c"` does not discard leading whitespace so it was taking the `'\n'` left in `stdin` by the previous `scanf()` call as your input, so you must add a space in the format string to make that happen. – David C. Rankin Nov 13 '20 at 20:13
  • This code does not support hitting return between the value that gets read into `b` and the character that gets read into `o`. So your input would have to be something like "3 + 7N" and you would never see the "Do you want to exit" prompt before having to enter whether or not you'd like to exit. – David Schwartz Nov 13 '20 at 20:16

0 Answers0