How can I clear an input buffer in C?
Asked Answered
L

20

117

I have the following program:

int main(int argc, char *argv[])
{
    char ch1, ch2;
    printf("Input the first character:"); // Line 1
    scanf("%c", &ch1);
    printf("Input the second character:"); // Line 2
    ch2 = getchar();

    printf("ch1=%c, ASCII code = %d\n", ch1, ch1);
    printf("ch2=%c, ASCII code = %d\n", ch2, ch2);

    system("PAUSE");
    return 0;
}

As the author of the above code has explained: The program will not work properly because at Line 1 when the user presses Enter, it will leave in the input buffer 2 characters: the Enter key (ASCII code 13) and \n (ASCII code 10). Therefore, in Line 2, it will read the \n and will not wait for the user to enter a character.

OK, I got this. But my first question is: Why doesn't the second getchar() (ch2 = getchar();) read the Enter key (13), rather than the \n character?

Next, the author proposed two ways to solve such problems:

  1. use fflush()

  2. write a function like this:

void
clear (void)
{
    while ( getchar() != '\n' );
}

This code worked actually. But I cannot explain how it works. Because in the while statement, we use getchar() != '\n', that means read any single character except '\n'? If so, does the '\n' character still remain in the input buffer?

Lissotrichous answered 26/10, 2011 at 2:48 Comment(3)
See also: I am not able to flush stdin. How can I flush stdin in C?Farthest
To be clear, "Enter key" is not a character. What you call "Enter key" is the carriage return character (\r). When you press Enter, depending on your system, it may emit a \r (old Macs), \r\n (Windows) or a \n (virtually every other OS, including OSX/macOS). The answers already cover how the C runtime collapses the Windows \r\n to just \n on text mode streams for you.Hexone
Does this answer your question? How to completely clear stdin and the \n before scanf()Allay
I
132

The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: Enter key (ASCII code 13) and \n (ASCII code 10). Therefore, at Line 2, it will read the \n and will not wait for the user to enter a character.

The behavior you see at line 2 is correct, but that's not quite the correct explanation. With text-mode streams, it doesn't matter what line-endings your platform uses (whether carriage return (0x0D) + linefeed (0x0A), a bare CR, or a bare LF). The C runtime library will take care of that for you: your program will see just '\n' for newlines.

If you typed a character and pressed enter, then that input character would be read by line 1, and then '\n' would be read by line 2. See I'm using scanf %c to read a Y/N response, but later input gets skipped. from the comp.lang.c FAQ.

As for the proposed solutions, see (again from the comp.lang.c FAQ):

which basically state that the only portable approach is to do:

int c;
while ((c = getchar()) != '\n' && c != EOF) { }

Your getchar() != '\n' loop works because once you call getchar(), the returned character already has been removed from the input stream.

Also, I feel obligated to discourage you from using scanf entirely: Why does everyone say not to use scanf? What should I use instead?

Independent answered 26/10, 2011 at 3:44 Comment(7)
This will hang waiting for the user to press Enter. If you want to simply clear stdin, use termios directly. https://mcmap.net/q/189209/-fflush-is-not-working-in-linuxAmias
@Amias Your comment doesn't make sense since pressing Enter isn't required to clear stdin; it's required to get input in the first place. (And that's the only standard way to read input in C. If you want to be able to read keys immediately, then you'll have to use non-standard libraries.)Independent
@Independent On Linux, getchar() will wait for the user to press Enter. Only then will they break out of the while loop. As far as I'm aware, termios is a standard library.Amias
@Amias No, you're wrong on both counts. This question is about how about clearing the remaining input from stdin after reading input, and in standard C, providing that input first requires typing a line and pressing Enter. After that line has been entered, getchar() will read and return those characters; a user will not need to press Enter another time. Furthermore, while termios might be common on Linux, it is not part of the C standard library.Independent
what is the reason for scanf(" %c", &char_var) working and ignoring the newline just by adding a space befor %c specifier?Recor
@CătălinaSîrbu scanf collapses all whitespace and treats all whitespace as equivalent. For example, a space in the format string will match any number of newlines, spaces, and tabs, and also can match nothing.Independent
Using scanf itself is never a good practice. getline/fgets with sscanf is better. Whether or not the whitespace collapsing behavior of the scanf-family of functions is desirable depends on your situation.Independent
A
54

You can do it (also) this way:

fseek(stdin,0,SEEK_END);
Albescent answered 17/3, 2012 at 13:36 Comment(9)
Wow... btw, does standard say fseek is available for stdin?Parnassus
I don't know, I think it doesn't mention it, but stdin is FILE* and fseek accepts a FILE* parameter. I tested it and it works on Mac OS X but not on Linux.Albescent
Please explain. It will be a great answer if the author would write implications of this method. Are there any issues?Tailback
@EvAlex: there are many issues with this. If it works on your system, great; if not, then it is not surprising as nothing guarantees that it will work when standard input is an interactive device (or a non-seekable device like a pipe or a socket or a FIFO, to name but a few other ways in which it can fail).Marte
Why it should be SEEK_END? Can we use SEEK_SET instead? How is the FP stdin behave?Credible
Works like a charm on Windows! Much cleaner and better way of flushing the keyboard buffer than using a loop as suggested by others. Thanks a ton!Anachronous
@ikh: No, it is not. SEEK_END cannot be used with text streams. So, this as bad as fflush(stdin).Fromma
it does not work. When choosing grid from 1 to 9 elements I can enter '95' and it will choose 9 then 5.Casiecasilda
Doesn't work on Linux.Watercool
O
21

A portable way to clear up to the end of a line that you've already tried to read partially is:

int c;

while ( (c = getchar()) != '\n' && c != EOF ) { }

This reads and discards characters until it gets \n which signals the end of the file. It also checks against EOF in case the input stream gets closed before the end of the line. The type of c must be int (or larger) in order to be able to hold the value EOF.

There is no portable way to find out if there are any more lines after the current line (if there aren't, then getchar will block for input).

Ovoviviparous answered 28/9, 2014 at 2:47 Comment(8)
why while((c=getchar())!=EOF); does not work? It is endless loop. Not able to understand the location of EOF in stdin.Credible
@Credible That would clear until the input stream is closed, which it won't be if there is more input to come laterOvoviviparous
@Credible Yes, you are correct. If there is nothing on stdin to flush when this gets called, it will block(hang) due to it being caught in an infinite loop.Confederacy
@Ovoviviparous The value of EOF is -1 so why char is not good as ultimately we are taking characters only.Sarita
@AbhishekMane The character 0xFF octal 0377 is also -1 in 8 bits. EOF needs to be different to that too -- it is -1 in 32 bits. All 8-bit chars can be used as data.Solutrean
@Solutrean both 0xFF & octal 0377 decimal values is 255. 255 don't represent -1 right ? 256 does. If I am missing something please correct me.Sarita
@AbhishekMane But a byte is 8 bits, and 256 takes 9 bits. You cannot handle any 8-bit value, plus one additional flag value, if you assign the result from getchar() to a char. Also, stdio.h has #define EOF (-1). C has char, signed char, unsigned char, and char may be in 0..255 or -128..127 depending on architecture. man getchar is very explicit: "fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error." So (int) -1 or (int) 0..255. Stuffing it into a char variable discards essential information.Solutrean
@Solutrean got it. Thanks. EOF is not character. getchar() returns char(0,1,2,...255) + EOF To handle this EOF only return type of getchar(_) is int . So C must be int right ?Sarita
V
14

The lines:

int ch;
while ((ch = getchar()) != '\n' && ch != EOF)
    ;

doesn't read only the characters before the linefeed ('\n'). It reads all the characters in the stream (and discards them) up to and including the next linefeed (or EOF is encountered). For the test to be true, it has to read the linefeed first; so when the loop stops, the linefeed was the last character read, but it has been read.

As for why it reads a linefeed instead of a carriage return, that's because the system has translated the return to a linefeed. When enter is pressed, that signals the end of the line... but the stream contains a line feed instead since that's the normal end-of-line marker for the system. That might be platform dependent.

Also, using fflush() on an input stream doesn't work on all platforms; for example it doesn't generally work on Linux.

Virnelli answered 26/10, 2011 at 3:14 Comment(2)
Note: while ( getchar() != '\n' ); is an infinite loop should getchar() return EOF due to end-of-file.Whoopee
To check for EOF as well, int ch; while ((ch = getchar()) != '\n' && ch != EOF); can be usedVirnelli
U
10

But I cannot explain myself how it works? Because in the while statement, we use getchar() != '\n', that means read any single character except '\n'?? if so, in the input buffer still remains the '\n' character??? Am I misunderstanding something??

The thing you may not realize is that the comparison happens after getchar() removes the character from the input buffer. So when you reach the '\n', it is consumed and then you break out of the loop.

Ungava answered 26/10, 2011 at 3:12 Comment(0)
D
8

scanf is a strange function, and there's a classic line from the movie WarGames that's relevant: "The only winning move is not to play".

If you find yourself needing to "flush input", you have already lost. The winning move is not to search desperately for some magic way to flush the nettlesome input: instead, what you need to do is to do input in some different (better) way, that doesn't involve leaving unread input on the input stream, and having it sit there and cause problems, such that you have to try to flush it instead.

There are basically three cases:

  1. You are reading input using scanf, and it is leaving the user's newline on the input stream, and that stray newline is wrongly getting read by a later call to getchar or fgets. (This is the case you were initially asking about.)

  2. You are reading input using scanf, and it is leaving the user's newline on the input stream, and that stray newline is wrongly getting read by a later call to scanf("%c").

  3. You are reading numeric input using scanf, and the user is typing non-numeric text, and the non-numeric text is getting left on the input stream, meaning that the next call to scanf fails on it also.

In all three cases, it may seem like the right thing to do is to "flush" the offending input. And you can try, but it's cumbersome at best and impossible at worst. In the end I believe that trying to flush input is the wrong approach, and that there are better ways, depending on which case you were worried about:

In case 1, the better solution is, do not mix calls to scanf with other input functions. Either do all your input with scanf, or do all your input with getchar and/or fgets. To do all your input with scanf, you can replace calls to getchar with scanf("%c") — but see point 2. Theoretically you can replace calls to fgets with scanf("%[^\n]%*c"), although this has all sorts of further problems and I do not recommend it. To do all your input with fgets even though you wanted/needed some of scanf's parsing, you can read lines using fgets and then parse them after the fact using sscanf.

In case 2, the better solution is, never use scanf("%c"). Use scanf(" %c") instead. The magic extra space makes all the difference. (There's a long explanation of what that extra space does and why it helps, but it's beyond the scope of this answer.)

And in case 3, I'm afraid that there simply is no good solution. scanf has many problems, and one of its many problems is that its error handling is terrible. If you want to write a simple program that reads numeric input, and if you can assume that the user will always type proper numeric input when prompted to, then scanf("%d") can be an adequate — barely adequate — input method. But perhaps your goal is to do better. Perhaps you'd like to prompt the user for some numeric input, and check that the user did in fact enter numeric input, and if not, print an error message and ask the user to try again. In that case, I believe that for all intents and purposes you cannot meet this goal based around scanf. You can try, but it's like putting a onesie on a squirming baby: after getting both legs and one arm in, while you're trying to get the second arm in, one leg will have wriggled out. It is just far too much work to try to read and validate possibly-incorrect numeric input using scanf. It is far, far easier to do it some other way.

You will notice a theme running through all three cases I listed: they all began with "You are reading input using scanf...". There's a certain inescapable conclusion here. See this other question: What can I use for input conversion instead of scanf?

Now, I realize I still haven't answered the question you actually asked. When people ask, "How do I do X?", it can be really frustrating when all the answers are, "You shouldn't want to do X." If you really, really want to flush input, then besides the other answers people have given you here, two other good questions full of relevant answers are:

Dyewood answered 15/10, 2021 at 15:59 Comment(0)
D
6

You can try

scanf("%c%*c", &ch1);

where %*c accepts and ignores the newline.

One more method

Instead of fflush(stdin), which invokes undefined behaviour, you can write

while((getchar()) != '\n');

Don't forget the semicolon after the while loop.

Departed answered 12/4, 2015 at 5:57 Comment(2)
1) "%*c" scans any character ( and does not save it), be it a newline or something else. Code is relying on that the 2nd character is a new line. 2) while((getchar())!='\n'); is an infinite loop should getchar() return EOF due to end-of-file.Whoopee
the second method depends on the condition like newline,null character,EOF etc(above it was newline)Departed
M
4

I am surprised nobody mentioned this:

scanf("%*[^\n]");
Monacid answered 1/11, 2020 at 21:25 Comment(0)
F
2

How can I flush or clear the stdin input buffer in C?

The fflush() reference on the cppreference.com community wiki states (emphasis added):

For input streams (and for update streams on which the last operation was input), the behavior is undefined.

So, do not use fflush() on stdin.

If your goal of "flushing" stdin is to remove all chars sitting in the stdin buffer, then the best way to do it is manually with either getchar() or getc(stdin) (the same thing), or perhaps with read() (using stdin as the first argument) if using POSIX or Linux.

The most-upvoted answers here and here both do this with:

int c;
while ((c = getchar()) != '\n' && c != EOF);

I think a clearer (more-readable) way is to do it like this. My comments, of course, make my approach look much longer than it is:

/// Clear the stdin input stream by reading and discarding all incoming chars up
/// to and including the Enter key's newline ('\n') char. Once we hit the
/// newline char, stop calling `getc()`, as calls to `getc()` beyond that will
/// block again, waiting for more user input.
/// - I copied this function
///   from "eRCaGuy_hello_world/c/read_stdin_getc_until_only_enter_key.c".
void clear_stdin()
{
    // keep reading 1 more char as long as the end of the stream, indicated by
    // `EOF` (end of file), and the end of the line, indicated by the newline
    // char inserted into the stream when you pressed Enter, have NOT been
    // reached
    while (true)
    {
        int c = getc(stdin);
        if (c == EOF || c == '\n')
        {
            break;
        }
    }
}

I use this function in my two files here, for instance. See the context in these files for when clearing stdin might be most-useful:

  1. array_2d_fill_from_user_input_scanf_and_getc.c
  2. read_stdin_getc_until_only_enter_key.c

Note to self: I originally posted this answer here, but have since deleted that answer to leave this one as my only answer instead.

Farthest answered 10/4, 2022 at 1:23 Comment(0)
S
1

I encounter a problem trying to implement the solution

while ((c = getchar()) != '\n' && c != EOF) { }

I post a little adjustment 'Code B' for anyone who maybe have the same problem.

The problem was that the program kept me catching the '\n' character, independently from the enter character, here is the code that gave me the problem.

Code A

int y;

printf("\nGive any alphabetic character in lowercase: ");
while( (y = getchar()) != '\n' && y != EOF){
   continue;
}
printf("\n%c\n", toupper(y));

and the adjustment was to 'catch' the (n-1) character just before the conditional in the while loop be evaluated, here is the code:

Code B

int y, x;

printf("\nGive any alphabetic character in lowercase: ");
while( (y = getchar()) != '\n' && y != EOF){
   x = y;
}
printf("\n%c\n", toupper(x));

The possible explanation is that for the while loop to break, it has to assign the value '\n' to the variable y, so it will be the last assigned value.

If I missed something with the explanation, code A or code B please tell me, I’m barely new in c.

hope it helps someone

Smasher answered 20/4, 2017 at 15:26 Comment(1)
You should deal with your "expected" character(s) inside of the while loop. After the loop you can consider stdin to be clean/clear and y will hold either '\n' or EOF. EOF is returned when there is no newline present and the buffer is exhausted (if the input would overflow the buffer before [ENTER] was pressed). -- You effectively use the while((ch=getchar())!='\n'&&ch!=EOF); to chew up each and every character in the stdin input buffer.Tented
T
0
unsigned char a=0;
if(kbhit()){
    a=getch();
    while(kbhit())
        getch();
}
cout<<hex<<(static_cast<unsigned int:->(a) & 0xFF)<<endl;

-or-

use maybe use _getch_nolock() ..???

Trysail answered 19/8, 2014 at 12:28 Comment(2)
The question is about C, not C++.Tortola
Note that kbhit() and getch() are functions declared in <conio.h> and only available as standard on Windows. They can be emulated on Unix-like machines, but doing so requires some care.Marte
F
0

Try this:

stdin->_IO_read_ptr = stdin->_IO_read_end;

Flora answered 25/7, 2020 at 18:25 Comment(1)
Please add a bit more details about how this solution works and how it is a useful way to solve the problem stackoverflow.com/help/how-to-answerValid
C
0

In brief. Putting the line...

while ((c = getchar()) != '\n') ;

...before the line reading the input is the only guaranteed method. It uses only core C features ("conventional core of C language" as per K&R) which are guaranteed to work with all compilers in all circumstances.

In reality you may choose to add a prompt asking a user to hit ENTER to continue (or, optionally, hit Ctrl-D or any other button to finish or to perform other code):

printf("\nPress ENTER to continue, press CTRL-D when finished\n");    
while ((c = getchar()) != '\n') {
        if (c == EOF) {
            printf("\nEnd of program, exiting now...\n");
            return 0;
        }
        ...
    }

There is still a problem. A user can hit ENTER many times. This can be worked around by adding an input check to your input line:

while ((ch2 = getchar()) < 'a' || ch1 > 'Z') ;

Combination of the above two methods theoretically should be bulletproof. In all other aspects the answer by @jamesdlin is the most comprehensive.

Crowns answered 21/7, 2021 at 14:56 Comment(0)
I
0

Quick solution is to add a 2nd scanf so that it forces ch2 to temporarily eat the carriage return. Doesn't do any checking so it assumes the user will play nice. Not exactly clearing the input buffer but it works just fine.

int main(int argc, char *argv[])
{
  char ch1, ch2;
  printf("Input the first character:"); // Line 1
  scanf("%c", &ch1); 
  scanf("%c", &ch2); // This eats '\n' and allows you to enter your input
  printf("Input the second character:"); // Line 2
  ch2 = getchar();

  printf("ch1=%c, ASCII code = %d\n", ch1, ch1);
  printf("ch2=%c, ASCII code = %d\n", ch2, ch2);

  system("PAUSE");  
  return 0;
}
Immobile answered 15/10, 2021 at 15:31 Comment(0)
W
0

I have written a function (and tested it too) which gets input from stdin and discards extra input (characters). This function is called get_input_from_stdin_and_discard_extra_characters(char *str, int size) and it reads at max "size - 1" characters and appends a '\0' at the end.

The code is below:


/* read at most size - 1 characters. */
char *get_input_from_stdin_and_discard_extra_characters(char *str, int size)
{

    char c = 0;
    int num_chars_to_read = size - 1;
    int i = 0;

    if (!str)
        return NULL;

    if (num_chars_to_read <= 0)
        return NULL;

    for (i = 0; i < num_chars_to_read; i++) {

        c = getchar();

        if ((c == '\n') || (c == EOF)) {
            str[i] = 0;
            return str;
        }

        str[i] = c;

    } // end of for loop

    str[i] = 0;

    // discard rest of input
    while ((c = getchar()) && (c != '\n') && (c != EOF));

    return str;

} // end of get_input_from_stdin_and_discard_extra_characters

Wexler answered 30/10, 2021 at 9:31 Comment(0)
E
0

Just for completeness, in your case if you actually want to use scanf which there are plenty of reasons not to, I would add a space in front of the format specifier, telling scanf to ignore all whitespace in front of the character:

scanf(" %c", &ch1);

See more details here: https://en.cppreference.com/w/c/io/fscanf#Notes

Erbil answered 18/11, 2022 at 8:50 Comment(0)
V
0

First, you should use variable of type int instead char for reading from input-output streams (at least in Linux).

Second, after the first read in Linux ONLY '\n' left in stdin (it is different in Windows). So you could use an extra variable to clear the buffer after the first read in your example. For example, your code can be like following:

int cr;
cr = fgetc(stdin);
Varices answered 26/8, 2023 at 11:16 Comment(0)
E
0

The following does on Linux.

fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
while(getchar() != EOF)
  ;
Erfert answered 11/9, 2023 at 19:25 Comment(0)
C
-1

Short, portable and declared in stdio.h

stdin = freopen(NULL,"r",stdin);

Doesn't get hung in an infinite loop when there is nothing on stdin to flush like the following well know line:

while ((c = getchar()) != '\n' && c != EOF) { }

A little expensive so don't use it in a program that needs to repeatedly clear the buffer.

Stole from a coworker :)

Confederacy answered 13/7, 2017 at 18:32 Comment(6)
Does not work on Linux. Use termios directly instead. https://mcmap.net/q/189209/-fflush-is-not-working-in-linuxAmias
Could you detail why the well known line is a possible infinite loop?Monniemono
The whole reason freopen exists is that you can't portably assign to stdin. It's a macro.Mingmingche
ishmael : All of our computers here in Cyber Command are Linux and it works fine on them. I tested it on both Debian and Fedora.Confederacy
What you call an "infinite loop" is the program waiting for input. That's not the same thing.Independent
@JasonEnochs All of our computers here in Cyber Command are Linux and it works fine on them. "I haven't observed it to fail - yet" is an awfully low standard to write code to. port70.net/~nsz/c/c11/n1570.html#note272 "The primary use of the freopen function is to change the file associated with a standard text stream (stderr, stdin, or stdout), as those identifiers need not be modifiable lvalues to which the value returned by the fopen function may be assigned."Infinite
U
-1

Another solution not mentioned yet is to use: rewind(stdin);

Ulphia answered 26/3, 2018 at 2:40 Comment(1)
That will completely break the program if stdin is redirected to a file. And for interactive input it's not guaranteed to do anything.Mingmingche

© 2022 - 2025 — McMap. All rights reserved.