0

I am teaching C language basic program and there is this point that I have noticed.

#include<stdio.h>
#include<conio.h>
void main(){
    int a;
    float b;
    char c;
    printf("Enter a number");
    scanf("%d",&a);
    printf("\nEnter a Float");
    scanf("%f",&b);
    printf("\nEnter a character");
    scanf("%c",&c);
    printf("Number is %d",a);
    printf("Float Number is %f",b);
    printf("Character is %c",c);
}

When running this simple code, I am able to enter value of int and float but then the program just runs without letting me insert the value of character. Now I know the solution is to put the character scanf function first but what I do not get it why is it happening?

Bhaumik Bhatt
  • 416
  • 7
  • 20
  • The character read by the `scanf("%c", &c)` is the newline after the floating-point number. You can demonstrate this by typing `3.14X` and seeing that `X` is read next; the `X` is left in the input because it isn't part of a valid number, so it is read by the call to`scanf()` that reads a character. Similarly, a newline isn't part of a valid number, so it is read by the call to `scanf()` that reads a character. You should check the return value from `scanf()` to ensure that an input is read. You should terminate your outputs — as opposed to prompts — with newlines. Use `printf("[%c]\n", c)`. – Jonathan Leffler Jul 05 '21 at 03:44

0 Answers0