Reputation: 184
I have the following C++ console based application that reads indefinitely from the user, and terminates only when the user types the command "bye".
Targeted platform is Windows, and compiler used is MS Visual Studio Enterprise 2015.
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
void ReadInput(void)
{
string x;
while (x != "bye")
{
getline(cin, x);
cout << x << endl;
}
}
BOOL CtrlHandler(DWORD fdwCtrlType)
{
switch (fdwCtrlType)
{
case CTRL_C_EVENT:
ReadInput();
return TRUE;
default:
return FALSE;
}
}
int main(void)
{
SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
ReadInput();
return 0;
}
What I'm trying to do is whenever the user presses ctr-c, CtrlHandler will catch it "re-open the shell via ReadInput()", however, that's not what's happening, the program goes into an infinite loop instead.
My objective is not to allow the user to terminate the console application by pressing ctrl-c, it should terminates only when the user types the command "bye".
Is it even possible to disable the event ctrl-c all together for my console window?
Your input is greatly appreciated.
Upvotes: 1
Views: 1249
Reputation: 184
It turns out that I need to check for the flags cin.fail() and cin.eof(), and if any of those is set, I clear cin's state with cin.clear().
Upvotes: 2