How does this work?

After hours of research, I've finally found a way to only have to press Enter ONCE to continue.

Before, if I didn't have input I would have to press Enter twice to continue using this code. However, it works fine when I have input using cin >> , which is expected.
1
2
3
4
5
6
7
8
void wait()
{
	cout << "\nPress enter to continue . . .";

	cin.clear();
	cin.ignore(numeric_limits<streamsize>::max(), '\n');
	cin.get();
}


After fumbling around and wasting a few hours of my life, I figured a way to do it regardless of whether I have/don't have input.
1
2
3
4
5
6
7
8
9
10
void wait()
{
	cout << "\nPress enter to continue . . .";

	cin.clear();					// clear the error flags set in the input stream
	cin.ignore(cin.rdbuf()->in_avail());		// ???

	char ch[1];
	cin.getline(ch, 1);
}

But I don't know how it works, especially cin.ignore(cin.rdbuf()->in_avail()) .
Anyone care to explain?
Last edited on
std::cin.rdbuf() returns a pointer to the stream buffer associated with std::cin
http://en.cppreference.com/w/cpp/io/basic_ios/rdbuf

std::streambuf::in_avail returns the number of characters available in the get area of the streambuf
(or -1 if no characters are available).
http://en.cppreference.com/w/cpp/io/basic_streambuf/in_avail

1
2
3
4
const auto chars_available = std::cin.rdbuf()->in_avail() ; 

if( chars_available > 0 ) // if there are some characters in the input buffer 
    std::cin.ignore(chars_available) ; // extract and discard the characters 
Why so complicated?

You could use getche(), getch() or while(!kbhit()); declared in conio.h
Because getche(), getch() or while(!kbhit()) are unavailable on many platforms, they are non-standard and conio.h might be removed in the future.
...because conio.h is non-standard and doesn't always behave.

Further, in_avail() is not actually required to return anything useful.


I maintain (and will always maintain) that the best and most correct way to do this is to remember this one lemma:

    The user will always press ENTER after every input.  

The corollary is this:

    Your code should always consume that newline after every input.

Live by this and you will not have any surprises to deal with.


If you want more on the complexities of managing this with pure C++, take a look at Narue's article at Daniweb: https://www.daniweb.com/programming/software-development/threads/90228/flushing-the-input-stream

Alas.
Topic archived. No new replies allowed.