Re: Using std::cin.rdbuf()->in_avail()
if (std::cin >> ch) {
You realise the above skips whitespace?
Yes.
std::cin.sync(); // flush remaining characters
cin.sync() doesn't do anything.
Surprisingly, it helped, although I accept that its behaviour is
unspecified. Since I was reading only a character at a time (std::cin >>
ch), the new-line character remained unread and interfered with processing
later on whilst .sync() appeared to clear that. My logic at the time was
that since sync() is supposed to work for std::istream like .flush() for
std::ostream and since the latter flushes whatever we have to the real
destination, sync() would synchronise the internal buffer with the real
input source, i.e. clear the buffer. But I turned to using
std::cin.ignore(std::cin.rdbuf()->in_avail()).
Usually, under these circumstances, you would wait for signals on two
object, std::cin's Windows file handle (get it with
GetStdHandle(STD_INPUT_HANDLE)) and an event object FINISHED. e.g.
HANDLE hFinished = CreateEvent(NULL, FALSE, FALSE, NULL);
//...
HANDLE hStdInput = GetStdHandle(STD_INPUT_HANDLE);
HANDLE const hArray[2] = {hFinished, hStdInput};
bool finished = false;
while (!finished)
{
DWORD ret = WaitForMultipleObjects(2, hArray, FALSE, INFINITE);
switch (ret)
{
case WAIT_OBJECT_0:
finished = true;
return; //finished
case WAIT_OBJECT_0 + 1:
{
char c;
if (std::cin.get(c))
{
//deal with c
}
//flush everything else?
std::cin.ignore(std::cin.rdbuf()->in_avail());
FlushConsoleInputBuffer(hStdInput);
}
break;
default:
//error handling
}
}
The code to exit should call:
SetEvent(hFinished);
Thank you. I did not realise I could wait on STD_INPUT_HANDLE.
Paul