Reputation: 1133
I'm trying to read console input in a loop, using Win32 API. I'm using the following (simplified) code:
do {
WriteConsoleW(hStdout, L"Enter text: ", wcslen(L"Enter text: "), NULL, NULL);
if (!ReadConsoleW(hStdin, buf, 1, &nCharsRead, NULL)) {
// ... Handle error...
}
if (!FlushConsoleInputBuffer(hStdin)) {
// ... Handle error ...
}
// ... Handle input ...
} while (!bValid);
However, for any length of input, unless I'm quitting the loop - ReadConsoleW will keep reading one character at a time (including the line break), but even after the FlushConsoleInputBuffer call the rest of the input will not be discarded. For example, if I'll enter a single letter - I'll see "Enter text: " printed three times. For 2 letters input it would be 4 prints, and so on. According to the FlushConsoleInputBuffer documentation, the console input buffer should be cleaned:
Flushes the console input buffer. All input records currently in the input buffer are discarded
Is there a bug in this function, or am I doing it wrong?
Upvotes: 2
Views: 830
Reputation: 11
The ReadConsoleW function adds the line break caused by the enter key as two additional characters.
Upvotes: 1