I'm writing a simple, universal function that shows a dialog. I intend to call it from different places in my code. The problem is that I need to clear the input buffer at the beginning of the function so lingering data from previous input is not interpreted as an answer.
This has to be a pretty common think to do, so I believe that C++ standard library provide some function that does that. However, I haven't any luck in finding it.
Here is a practical example of what I want to accomplish:
#include <iostream>
#include <string>
unsigned dialog(const char question[], const char answers[])
{
//TODO reset std::cin
while (true)
{
std::cout << question << " [";
for (unsigned i = 0; answers[i] != '\0'; ++i)
{
if (i != 0)
std::cout << '/';
std::cout << answers[i];
}
std::cout << ']' << std::endl;
std::string line;
std::getline(std::cin, line);
if (line.empty())
{
for (unsigned i = 0; answers[i] != '\0'; ++i)
if (answers[i] >= 'A' && answers[i] <= 'Z')
return i;
} else if (line.length() == 1)
{
const char answer = toupper(line[0]);
for (unsigned i = 0; answers[i] != '\0'; ++i)
if (answer == toupper(answers[i]))
return i;
}
}
}
int main()
{
// --- optional part ---
std::cout << "Write something to clutter the input buffer..." << std::endl;
std::string foo;
std::cin >> foo; //User enters "aaa bbb ccc"
// --- optional part end ---
return dialog("Do you like this question?", "Yn");
}
Unlike this other similar question, I'm looking for some portable solution. It should be supported in at least Windows and any Linux system.
There is also this question that is very similar to mine. However, all the answers seems to assume that input buffer is not empty at the moment. If I put it before my dialog and the input is empty at the moment (e.g. directly after start of the program), it leads to a situation when user needs to press Enter to even display my dialog on screen. A few answer from that question that don't assume that buffer is not empty, base on functions that depend on implementation of the standard library.