tags:

views:

42

answers:

1

This is my code

#include<stdio.h>

int main()
{

    char choice;

    printf("Do you want to enter a number:");
    scanf("%c",&choice);

    while(choice == 'y')
    {
      printf("Entered number\n");
      printf("Do you want to enter a number:");
      scanf("%c",&choice);


    }

    printf("End\n");

return 0;
}

and the output was

Do you want to enter a number:y
Entered number
Do you want to enter a number:End

for the first time, it checked whether my character is 'y' but in the loop after first time execution, it doesnot wait for user to type, it just terminates the loop . what might have gone wrong ? please help

+1  A: 

Take look at - http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1044873249&amp;id=1043284392

#include<stdio.h>

int main()
{
    char choice;

    printf("Do you want to enter a number:");
    scanf("%c",&choice);

    while (choice == 'y')
    {
        while ((choice = getchar()) != '\n' && choice != EOF);
        printf("Entered number\n");
        printf("Do you want to enter a number:");
        scanf("%c",&choice);
    }

    printf("End\n");

    return 0;
}

DONOT USE : fflush Why fflush(stdin) is wrong

adatapost