How to take input as a single character in C?

22 Views Asked by At

I am relatively new to programming and C language in general. I was trying to make a pretty simple project of a calculator. For that I needed to take input as a single character. I use the visual studio code IDE.

#include<stdio.h>
#include<conio.h>
char type;
float x,y;
int main(){
    printf("Please enter number 1: ");
    scanf("%f",&x);
    printf("Please enter number 2: ");
    scanf("%f",&y);
    printf("Please enter what do you want to do with the numbers, insert m for multiplication, insert d for division, insert a for addition and insert s for subtraction: ");
    scanf("%c",&type);

    if(type=='m'){
        printf("The result is: %f",x*y);
    }
    else if(type=='d'){
        printf("The result is: %f",x/y);
    }
    else if(type=='a'){
        printf("The result is: %f",x+y);
    }
    else if(type=='s'){
        printf("The result is: %f",x-y);
    }
    else{
        printf("Invalid Input");
    }
}

This is my code but when I run this, VS Code skips the scanf() function in the following line: scanf("%c",&type); It directly gives the output of 'Invalid Input'. Can someone please help me and tell me what I am doing wrong?

0

There are 0 best solutions below