0

First i call getchar() and enter some character on standard input/output , because scanf() can also fetch these characters , i want to empty the buffer , before calling scanf() , here is the program.

int main()
  {
    getchar();   // i input some characters here , "abcdefgh" 


    ------ // here i need some statement that will empty standard input/output.

    int a;
    scanf("%d",&a);  // so if buffer is empty, this prompt me to enter chacter.
                                    // if i enter 7 
    printf("%d",a);                // this should print 7

    }
siddstuff
  • 1,215
  • 4
  • 16
  • 37
  • 2
    You may use `fflush` on `stdin`, but you should know that it's non-standard and may not work on all systems. – Some programmer dude Jul 01 '13 at 12:51
  • printf("%d\n", a); //this should print 7... – Varvarigos Emmanouil Jul 01 '13 at 12:56
  • Please detail your goal. It appears to me `getchar()` executes by waiting for input. You begin to type in "abc...". But after you type 'a', `getchar()` completes and your desired "empty standard input/output" will execute before you have had time to type "bc...". Thus not flushing out the "bc..." before `scanf()` executes. Your thoughts? – chux - Reinstate Monica Jul 02 '13 at 00:37

2 Answers2

0

Use fflush(stdin). From manpage of fflush():

For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application. The open status of the stream is unaffected.

However note that this is not standard.
You can also do this:

while((c = getchar()) != '\n' && c != EOF)
    /* discard */ ;

This will discard all extra characters till newline.
For output buffers use: fflush(stdout);

mohit
  • 5,696
  • 3
  • 24
  • 37
0

Flushing input stream is undefined behavior. For output buffers try this :

fflush(stdout);

setbuf(stdout,NULL);

You could also try fpurge The function fpurge() erases any input or output buffered in the given stream. For output streams this discards any unwritten output. For input streams this discards any input read from the underlying object. NOTE: fpurge is nonstandard and not portable.

Just take a look at this post on stackoverflow:I am not able to flush stdin

Community
  • 1
  • 1
0decimal0
  • 3,884
  • 2
  • 24
  • 39