0

The program skips the scanf("%c", operator) whenever I run this code (C). I am just learning C and find this confusing. The program is working as expected when I ask for the scanf("%c", operator) before asking for any other input. What is at play here?

#include <stdio.h>
#include <string.h>
int main() {
    
    char variable[2];
    char operator;
    int first, second;
    
    printf("Enter the variable: \n");
    scanf("%s", &variable);

    printf("Enter an operator (+, -): ");
    scanf("%c", &operator);

    printf("Enter two operands (one before equal and one after equal sign): ");
    scanf("%d %d", &first, &second);

    switch (operator) {
    case '+':
        printf("x = %d and x = %d", first + second, first - second);
        break;
    case '-':
        printf("x = %d and x = %d", first + second, first - second);
        break;
        // Absolute Value for simple calculations
    default:
        printf("Error! Difficult computation");
    }

    return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Salman
  • 9
  • 4
  • 1
    Please do not add unnecessary tags. C++ and C are two different programming languages. – Geno C Aug 14 '20 at 19:13
  • Be careful with `scanf("%s", variable)`, when the array is not long enough it will destroy your program. – Cosinus Aug 14 '20 at 19:28
  • This is not a duplicate! The problem is when you enter more than 1 character to `variable` the program is undefined. I think you could fix it with `char *variable; scanf("%ms", &variable); /* do something with variable */ free(variable);` – Cosinus Aug 14 '20 at 19:44

0 Answers0