0
#include "stdio.h"
#include "stdlib.h"

int main() {

    int  a = 10;
    float f;
    double d;
    char k = 'X';

    scanf("%d", &a);
    printf("%d\n", a);


    scanf("%f", &f);
    printf("%f\n", f);

    scanf("%lf" , &d);
    printf("%lf\n", d);

    fflush(stdin);

    scanf("%c",&k);
    printf("%c\n",k);



    return 0;
}

When I execute the code, I am only able to enter data until I enter a double value and then the program exits without asking for another input. Can someone please explain what is going on with this? I've been seeing online tutorials and the same code worked for them!

This is what I get, when I execute the program:

   21
   21
   333.264765
   333.264771
   2317.23
   2317.230000


   Program ended with exit code: 0

1 Answers1

1

fflush is usually used to flush the output buffer(output stream). fflush(stdin) may result in undefined behavior. Not all compilers support this operation. This link may help

Community
  • 1
  • 1
Reena Cyril
  • 417
  • 4
  • 11
  • What can i do to make the code work without using fflush(stdin) – Kartik Gupta Aug 03 '17 at 06:48
  • 1
    @KartikGupta add a space before `%c` as in [this answer](https://stackoverflow.com/a/5240807/4142924). – Weather Vane Aug 03 '17 at 06:56
  • 1
    "*may result in undefined behavior.*" <- no, it **is** *undefined behavior*. If it empties `stdin`'s buffer, this is still one possibility of undefined behavior ;) –  Aug 03 '17 at 07:06