0

I want this program show following.

Data input (Ctrl+Z to exit) : a
Data input (Ctrl+Z to exit) : b
Data input (Ctrl+Z to exit) : ^Z
sum : 2

But when I execute this code, Data input (Ctrl+Z to exit) : printed a few times.

For example, when I input 'A', of course 'A enter' 2 characters,then 2 times of "Data input (Ctrl+Z to exit) : " printed.

int main(void) 
{
    int cnt = 0;
    char input;

    while (1) {
        fputs("Data input (Ctrl+Z to exit) : ", stdout);
        input = getchar();

        if (input == EOF)
            break;

        fflush(stdin);
        cnt++;
    }
    printf("sum : %d", cnt);
    return 0;
}
mch
  • 9,424
  • 2
  • 28
  • 42
asking
  • 1

2 Answers2

0

getchar() reads one character from the standard input, but you have multiple characters in stdin (character you've entered plus \n for enter key), so when it goes to the second iteration of the loop it reads that leftover \n from stdin.

Solution: instead of fflush(stdin) use fpurge(stdin) to clear all the buffered data.

Edit: your system may luck fpurge though, it's non-standard BSD function. On libc-based system (Linux, e.g.) there's __fpurge (see https://www.gnu.org/software/libc/manual/html_node/Flushing-Buffers.html)

avysk
  • 1,973
  • 12
  • 18
  • `fflush(stdin)` and `fpurge` are both non-standard functions, so not portable. – Weather Vane Mar 03 '17 at 11:22
  • @WeatherVane From `man fflush`: `The fflush() function conforms to ISO/IEC 9899:1990 (``ISO C90'').` About `fpurge` I'm not sure. – avysk Mar 03 '17 at 11:25
  • Then please [read this](http://stackoverflow.com/a/18170435/4142924) which says *From C11 7.21.5.2 The fflush function, fflush works only with output/update stream, not input stream.* – Weather Vane Mar 03 '17 at 11:27
  • @WeatherVane That I'm very aware of. I never proposed to use `fflush` on input stream, it was original poster, not me. – avysk Mar 03 '17 at 11:28
  • For `fpurge` please [read this](http://man7.org/linux/man-pages/man3/fpurge.3.html) which says *These functions are nonstandard and not portable.* – Weather Vane Mar 03 '17 at 11:29
  • Yep, about `fpurge` I've said above "I'm not sure" :) Edited the answer to reflect this. – avysk Mar 03 '17 at 11:30
0

A simple way to read one char safely would be to use this function,

char readChar()
{
    char c;
    scanf(" %c" , &c);
    return c;
}

so in your code your can use

input = readChar();

and it will work.

SHAHS
  • 462
  • 1
  • 5
  • 13