Pur*_*ula 0 c++ windows loops cin infinite-loop
我有以下代码。它在键入后无限运行ctrl + c
并执行代码的默认部分。
// Program to build a simple calculator using switch Statement
#include <iostream>
using namespace std;
int main() {
char oper;
float num1, num2;
while(true){
cout << "Enter an operator (+, -, *, /): ";
cin >> oper;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;
switch (oper) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
// operator is doesn't match any case constant (+, -, *, /)
cout << "Error! The operator is not correct";
break;
}
cout<<endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:这是 C++ 中的正常行为吗?如果是的话,我们该如何解释呢?
如果你想在windows中捕获CTRL-C,则无法像linux那样通过signal()
. signal()
在 Windows 中无法SIGINT
正确处理。您需要用于SetConsoleCtrlHandler
此目的。
如果您不设置处理程序,应用程序 可能会决定忽略 CTRL-C。CTRL-BREAK 始终是一个信号,但 CTRL-C 可能不是:
CTRL+BREAK 始终被视为信号,但可以通过三种方式更改典型的 CTRL+C 行为,以防止调用处理程序函数:
1- SetConsoleMode函数可以禁用控制台输入缓冲区的ENABLE_PROCESSED_INPUT模式,因此 CTRL+C 被报告为键盘输入而不是信号。
2- 使用 NULL 和 TRUE 参数调用SetConsoleCtrlHandler会导致调用进程忽略 CTRL+C 信号。该属性由子进程继承,但任何进程都可以启用或禁用它,而不会影响现有进程。
3- 如果正在调试控制台进程并且未禁用 CTRL+C 信号,系统会生成DBG_CONTROL_C异常。引发此异常只是为了调试器的利益,应用程序永远不应该使用异常处理程序来处理它。如果调试器处理异常,应用程序将不会注意到 CTRL+C,但有一个例外:可警报等待将终止。如果调试器传递未处理的异常,则 CTRL+C 将传递到控制台进程并被视为信号,如前所述。
这是msdn文档。
归档时间: |
|
查看次数: |
905 次 |
最近记录: |