1

I am trying to getting an value in variable c which has an data type of character but it not ask me or wait me to enter the character

I have used fflush(stdin); this to flushing previous value if any but it wont work for me

int main()
{
int a =10;
float f;
double d;
char c ;

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",&c);
printf("%c \n",c);
return 0;
}

Here is what my output looks like

enter image description here

Pedro LM
  • 742
  • 4
  • 12
  • `fflush(stdin);` is questionable: [SO: what is the use of fflush(stdin) in c programming](https://stackoverflow.com/a/18170435/7478597). – Scheff's Cat Jun 01 '19 at 06:15
  • `fflush()` has undefined behaviour for input streams. `stdin` is an input stream. – Peter Jun 01 '19 at 06:15
  • 1
    Though this might compile in C++ as well, to me, it looks like a C question. Please, prevent tag spamming (and [edit] your question to remove one of the tags). – Scheff's Cat Jun 01 '19 at 06:16
  • 1
    I'm guessing the `scanf("%c")` is reading a lingering unread line break char from the previous `scanf("%lf")`. In C++, this is easy to deal with using `std::cin.ignore()`. In C, you can use `getline()` and discard what is read – Remy Lebeau Jun 01 '19 at 06:18
  • 1
    This seems a good reading concerning your issue: [SO: How to clear input buffer in C?](https://stackoverflow.com/a/7898516/7478597). – Scheff's Cat Jun 01 '19 at 06:22

1 Answers1

2

The left over \n from the scanf("%lf",&d); will be consumed at scanf("%c",&c);.
Hence the double line feed in the output.

This answer from the marked duplicate seems to provide a good workaround for the problem (emphasis mine):

scanf(" %c",&c);
    // ^

You can probably rescue it by using " %c" instead of "%c" for the format string. The blank causes scanf() to skip white space (including newlines) before reading the character.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190