I have a Qt gui application with commandline functionality.
To make this work I added this to the top of the main()
function:
#ifdef _WIN32
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
freopen("CONOUT$", "w", stdout);
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stderr);
}
#endif
Then an instance of my main class is constructed. In the constructor, QCommandLineParser
determines if there are any arguments, and either creates an instance of the cmdline parsing class, or the gui application class.
In the cmdline parsing class, I ask the user to input certain values:
QString qanswer;
// `answerToInt` is an std::unordered_map
while (answerToInt.find(qanswer) == answerToInt.end()) {
std::cout << std::endl << "File will be overwritten:" << std::endl
<< path.toStdString() << std::endl
<< "Are you sure? " << (multiple ? "(Yes/YesAll/No/NoAll)" : "(Yes/No)") << std::endl;
std::string answer;
std::cin >> answer;
qanswer = QString::fromStdString(answer).toLower();
std::cin.clear();
}
When "Yes" "No", "YesAll" or "NoAll" (case insensitive) is input, the program continues as expected, but when the user inputs something other than that, cmd throws this:
'[input]' is not recognized as an internal or external command [...]
And then the "C:\path\to\exe>" is displayed again, where the user can continue to input until one of the correct values is typed. Once a valid string is input, it continues again as expected.
I tried this answer as well as std::getline()
, but it makes no difference.
So how do I prevent the error from showing up and continue displaying the cout
?