简体   繁体   中英

How to trap ctrl-c event in a C++ console application on Windows without going into an infinite loop?

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.

事实证明,我需要检查标志cin.fail()cin.eof() ,并且如果设置了任何标志,则使用cin.clear()清除cin的状态。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM