0

Below is a simple program which I am trying to run, but unfortunately it doesn't work well, when I try to input for the second time, it doesn't take input.

#include <stdio.h>

int main(){
    int inpt, 
        pos = 0,
        neg = 0,
        zero = 0;
    char cont = 'y';

    while(cont == 'y' || cont == 'Y') {
        printf("\nPlease enter a Number: ");
        scanf("%d", &inpt);

        if( inpt < 0) {
            neg++;
        } else if( inpt > 0) {
            pos++;
        } else {
            zero++;
        }

        fflush(stdin);

        printf("\n Do you want to Continue:");
        scanf("%c", &cont);

        printf("\nvalue: %d", cont);
    }

    printf("\nTotal Number of Positive Integers: %d \n Total Number of Negative Integers: %d \n Total Number of Zeros: %d ", pos, neg, zero);

    return 0;
}

Fortunately, I tried debugging and printed the value for cont and found that it's 10(which is the ASCII value for Enter key in the keyboard). I was hoping that fflush should have cleared the input buffer but that doesn't seem to be the case.

Any suggestions on how to fix would be greatly appreciated.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
TheViralGriffin
  • 421
  • 1
  • 8
  • 21
  • 1
    `fflush(stdin);` is not well defined; On some platforms it does what you expect, but on many it is just a no-op – Ctx Feb 19 '20 at 17:19
  • is there an alternative for the fflush, i am currently using gcc in mac – TheViralGriffin Feb 19 '20 at 17:20
  • You have to consume the input, for example with `fgets()`. You might end up blocking, however, if no input is pending – Ctx Feb 19 '20 at 17:21
  • 3
    This is one of the most frequently asked questions, please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). – Weather Vane Feb 19 '20 at 17:22
  • If you want to read in a line of text and parse it, why not write code that reads a line of text and parses it? – David Schwartz Feb 19 '20 at 17:25

0 Answers0