0

This code is not working as it worked in CodeBlocks :

#include <stdio.h> 
#include <stdlib.h>

int main()
{
    char c;
    char choice;

    do
    {
        printf("Enter a character using getchar(): ");
        fflush(stdin);
        c = getchar();
        printf("The entered charcter is: ");
        putchar(c);
        do
        {
            printf("\nDo you want to continue [Y/N]: ");
            fflush(stdin);
            choice = getchar();
            if (choice >= 'a' && choice <= 'z')
                choice -= 32;
        } while (choice != 'Y' && choice != 'N');
        printf("\n");
    } while (choice == 'Y');

    system("pause");
    return 0;
}

The output is :

Enter a character using getchar(): !
The entered character is: !
Do you want to continue [Y/N]:
Do you want to continue [Y/N]: y

Enter a character using getchar(): The entered character is:

Do you want to continue [Y/N]:

Why is fflush(stdin) not working ?

Is there any other way solve this problem ?

cyberlobe
  • 1,783
  • 1
  • 18
  • 30

1 Answers1

3

fflush(stdin) is undefined, by the standard:

J.2 Undefined behavior

The stream for the fflush function points to an input stream or to an update stream in which the most recent operation was input (7.21.5.2).

So don't use it.

artm
  • 17,291
  • 6
  • 38
  • 54