120

How do I clear the cin buffer in C++?

Dana the Sane
  • 13,774
  • 8
  • 51
  • 77

13 Answers13

122

I would prefer the C++ size constraints over the C versions:

// Ignore to the end of file
cin.ignore(std::numeric_limits<std::streamsize>::max())

// Ignore to the end of line
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
Martin York
  • 234,851
  • 74
  • 306
  • 532
  • 17
    More importantly, the values might be different! (streamsize doesn't have to be int) –  Nov 16 '09 at 20:35
  • 2
    could you please cite an example where we need to ignore to the end of file because if I use `cin` and use the first statement above to flush the `cin` buffer, then it keeps prompting for input till I enter `EOF` by pressing `ctrl+d`? – ajay Oct 19 '13 at 19:39
  • @ajay: No. That is something you will need to decide. I am merely explaining what the above will do. – Martin York Oct 20 '13 at 00:52
108

Possibly:

std::cin.ignore(INT_MAX);

This would read in and ignore everything until EOF. (you can also supply a second argument which is the character to read until (ex: '\n' to ignore a single line).

Also: You probably want to do a: std::cin.clear(); before this too to reset the stream state.

Arslan Ali
  • 16,294
  • 7
  • 51
  • 65
Evan Teran
  • 80,654
  • 26
  • 169
  • 231
  • 11
    Clear before, rather than after, so the stream is put into a good state where it can operate on its buffer. – GManNickG Oct 03 '10 at 10:33
  • 3
    Just wanted to point out that for my case, I find the '\n' necessary. Otherwise subsequent "cin >>" doesn't work. – Cardin Nov 21 '13 at 09:39
  • For me this halts until it finds at least as many characters as the argument (microsoft compiler) – Nic Aug 23 '16 at 19:05
  • @Nic - of course, this tells the code to ignore ALL characters until the amount specified. In the main example, it will ignore essentially until `EOF` (because `INT_MAX` is huge). As mentioned in the post, if you just want to ignore a single line, you need to specify an extra parameter of `'\n` to tell it you only want to ignore up to the end of the line. – Evan Teran Aug 23 '16 at 20:08
  • If you do this the next time you call getline(cin, input) you can press a char followed by enter all day long it won't go through. – user3015682 May 23 '19 at 19:39
  • Because C++ file streams and C file streams don't share buffers. Each implementation does there own independent buffering using slightly different methodologies. – Evan Teran Feb 11 '20 at 13:40
24
cin.clear();
fflush(stdin);

This was the only thing that worked for me when reading from console. In every other case it would either read indefinitely due to lack of \n, or something would remain in the buffer.

EDIT: I found out that the previous solution made things worse. THIS one however, works:

cin.getline(temp, STRLEN);
if (cin.fail()) {
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
jyggorath
  • 409
  • 5
  • 10
14

I have found two solutions to this.

The first, and simplest, is to use std::getline() for example:

std::getline(std::cin, yourString);

... that will discard the input stream when it gets to a new-line. Read more about this function here.

Another option that directly discards the stream is this...

#include <limits>
// Possibly some other code here
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');

Good luck!

Ben
  • 141
  • 1
  • 4
10
int i;
  cout << "Please enter an integer value: ";

  // cin >> i; leaves '\n' among possible other junk in the buffer. 
  // '\n' also happens to be the default delim character for getline() below.
  cin >> i; 
  if (cin.fail()) 
  {
    cout << "\ncin failed - substituting: i=1;\n\n";
    i = 1;
  }
  cin.clear(); cin.ignore(INT_MAX,'\n'); 

  cout << "The value you entered is: " << i << " and its double is " << i*2 << ".\n\n";

  string myString;
  cout << "What's your full name? (spaces inclded) \n";
  getline (cin, myString);
  cout << "\nHello '" << myString << "'.\n\n\n";
Martin York
  • 234,851
  • 74
  • 306
  • 532
5

How about:

cin.ignore(cin.rdbuf()->in_avail());
Martin York
  • 234,851
  • 74
  • 306
  • 532
  • 3
    the streambuf's in_avail() function is unreliable, and many implementations just return zero. See: https://connect.microsoft.com/VisualStudio/feedback/details/509337/vc-8-9-sstream-basic-streambuf-sputc-sputn-dont-increment-gcount gnu's libc++ is similar – James Caccese Jun 03 '11 at 21:50
4

I prefer:

cin.clear();
fflush(stdin);

There's an example where cin.ignore just doesn't cut it, but I can't think of it at the moment. It was a while ago when I needed to use it (with Mingw).

However, fflush(stdin) is undefined behavior according to the standard. fflush() is only meant for output streams. fflush(stdin) only seems to work as expected on Windows (with GCC and MS compilers at least) as an extension to the C standard.

So, if you use it, your code isn't going to be portable.

See Using fflush(stdin).

Also, see http://ubuntuforums.org/showpost.php?s=9129c7bd6e5c8fd67eb332126b59b54c&p=452568&postcount=1 for an alternative.

Community
  • 1
  • 1
Shadow2531
  • 11,352
  • 5
  • 29
  • 40
  • 9
    fflush(stdin); is Undefined Behavior (in the C programming language), explicitly stated so in 7.18.5.2/2 – Cubbi Jan 15 '11 at 05:48
  • 1
    +1 for supplying a valid, working kludge. Some people have jobs others have standards. – Mikhail Jul 27 '12 at 16:18
  • 6
    @Mikhail: Your job should include writing standard compliant code. I will make sure to avoid using anything you have written in the future. – Ed S. Jan 04 '13 at 21:46
4

Another possible (manual) solution is

cin.clear();
while (cin.get() != '\n') 
{
    continue;
}

I cannot use fflush or cin.flush() with CLion so this came handy.

Bobul Mentol
  • 124
  • 6
4

Easiest way:

cin.seekg(0,ios::end);
cin.clear();

It just positions the cin pointer at the end of the stdin stream and cin.clear() clears all error flags such as the EOF flag.

1

The following should work:

cin.flush();

On some systems it's not available and then you can use:

cin.ignore(INT_MAX);
Martin York
  • 234,851
  • 74
  • 306
  • 532
Gunnar Steinn
  • 847
  • 2
  • 10
  • 23
1
#include <stdio_ext.h>

and then use function

__fpurge(stdin)
techcomp
  • 336
  • 2
  • 12
1

It worked for me. I have used for loop with getline().

cin.ignore()
Amrit Malla
  • 123
  • 6
0

cin.get() seems to flush it automatically oddly enough (probably not preferred though, since this is confusing and probably temperamental).

lennon310
  • 11,840
  • 11
  • 40
  • 55