fflush and fgetc question

This is a discussion on fflush and fgetc question within the Linux Programming forums, part of the Platform Specific Boards category; Code: int i; while(1) { fflush(stdin); i=fgetc(stdin); printf("%d\n",i); } i want to read the first character of the string i ...

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    167

    fflush and fgetc question

    Code:
    int i;
    
    while(1)
    {
       fflush(stdin);
       i=fgetc(stdin);
       printf("%d\n",i);
    }
    i want to read the first character of the string i enter:
    for example if I enter "1\n" it reads both the chars (2 cycles of the while) why doesn't the fflush resolve this?

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,484
    > why doesn't the fflush resolve this?
    Because it's undefined?
    Because you haven't read the FAQ?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Dec 2005
    Posts
    167
    ok... i understand now that. but how can I fix it without fflush(stdin) ?

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,484
    What do you want to fix?

    Perhaps
    if ( i != '\n' ) printf("%d\n",i);

    Or read a line using fgets(), then parse that line to decide whether you're interested in each character (or not).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21