5

When I use scanf more than one time the program do not wait for another input. Instead it exits

I learned that I could put a blank space before the conversion specifier in the scanf-function - yes that solved the problem and I guess that has to do with the inputstream, that is - if its a newline character in the inputstream the scanf will consume it immediately.

scanf(" %f", &value);

But if its so - why could I not use the fflush(stdin) instead? I have tried but it doesnt work.

#include <stdio.h>

int main(void)
{
    float value;
    char ch;

    printf("input value: ");
    scanf("%f", &value);
    fflush(stdin);
    printf("input char: ");
    scanf("%c", &ch);

    return 0;
}
Sam Protsenko
  • 14,045
  • 4
  • 59
  • 75
java
  • 1,165
  • 1
  • 25
  • 50
  • Where have you declared the variable "koppling"? – Corb3nik Apr 19 '15 at 13:47
  • What compiler/OS are you using? – P.P Apr 19 '15 at 13:55
  • @BlueMoon - gcc/ubuntu – java Apr 19 '15 at 14:04
  • Right. `fflush(stdin)` is undefine behaviour in standard C. But some implementations support it to flush `stdin`. For examle, the glibc on linux supports it but is non-standard. – P.P Apr 19 '15 at 14:09
  • POSIX as of late specifies some very particular behavior for [`fflush` on **seekable** input streams](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fflush.html), but it's probably best just to consider it undefined behavior anyway due to the requirements for using it on input streams successfully. –  Apr 19 '15 at 14:28

2 Answers2

8

fflush() is used for clearing output buffers. Since you are trying to clear an input buffer, this may lead to undefined behavior.

Here is an SO question explaining why this isn't good practice :

Using fflush(stdin)

Community
  • 1
  • 1
Corb3nik
  • 1,177
  • 7
  • 26
6

AS per the C11 standard document, chapter 7.21.5.2, fflush() function, (emphasis mine)

int fflush(FILE *stream);

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

so, basically, using fflush(stdin); is undefined behaviour.

To serve your purpose, while using %c format specifier, you can rewrite your code as

scanf(" %c", &ch);
       ^
       |
   notice here

the leading whitespace before %c skips all whitespace like character (including the \n stored by pressing previous ENTER key) and read the first non-whitespace character.

Note: as %d and %f specifiers already internally ignore the leading whitespaces, you don't need to speicy explicitly in those cases.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261