0

I did include the library <stdio.h> but the codes below leads to an infinite loop with VS 2015 (as well as GNU GCC):

//Sample Code
void main() {
char check;
do {
    check = '\0';
    printf("Enter a character > ");
    fflush(stdin);
    scanf("%c", &check);
    if (check == '\n') printf("\nERROR\n");
} while (check != '\n');
system("pause"); }

/*
Result:
Enter a character > r
Enter a character >
ERROR
Enter a character > ww
Enter a character > Enter a character >
ERROR
*/

But when I compiled it in my previous version of VS, which was 2013, it worked completely fine. So I have suspected that the fflush function no longer works with VS 2015.

Sorry, I'm new in C languages. So, according to what I have leant, using fflush(stdin) is actually a bad idea and this function has been marked as an undefined behavior.

But here are the real questions which are making me curious:

  1. Why does fflush(stdin) no longer work with VS2015?

  2. Is there anyway else to implement the "function" of fflush(stdin) that can be used in the code involved do-while loop (to prevent infinite loop)?

Thank you

Juen Khaw
  • 161
  • 1
  • 1
  • 10
  • but the method could not handle the case if user input more than one character at once. The code was working well with VS 2013. – Juen Khaw Jul 25 '15 at 15:34
  • No, it wasn't. It was just differently broken. `fflush(stdin)` has always been wrong, as is using `scanf` for user input. – melpomene Jul 25 '15 at 15:36
  • 1
    `fflush(stdin)` invokes UB as per the standard although some implementations define the behavior. Replacement for `fflush(stdin)` : `int c; while((c = getchar()) != '\n' && c != EOF);` – Spikatrix Jul 25 '15 at 15:38
  • so, `fflush` is always a bad idea to code, thx anyway. – Juen Khaw Jul 25 '15 at 15:48
  • None of the suggested answers are relevant to OP's question about VS2015 vs VS2013. – Thomas Dickey Jul 25 '15 at 16:26
  • I just curious about why did `fflush(stdin)` works with VS2013 but not with VS2015, and so far, i find no solution that could fulfill my needs. – Juen Khaw Jul 25 '15 at 16:35
  • [fflush](https://msdn.microsoft.com/en-us/library/9yky46tz.aspx) document of vs2015 is not change. – BLUEPIXY Jul 26 '15 at 01:30
  • Looking at the source code for fflush from VS2013 and VS2015, it seems fflush in VS2015 does nothing if the stream is not open for writing, whereas in VS2013 it would clear the input buffer unconditionally in addition to flushing output data. The MSDN documentation is out of date (or conversely, perhaps the fflush implementation is now broken). – Cameron Apr 08 '16 at 23:35

0 Answers0