发送 ctrl + z 到控制台程序
我有一个用 C 编写的简单控制台程序,想要使用 CTRL + Z 中止文本输入。怎么可能呢?
编辑:这是一些代码(未经测试)。
#include <stdio.h>
int main()
{
float var;
while(1)
{
scanf("%lf", &var); // enter a float or press CTRL+Z
if( ??? ) // if CTRL+Z was pressed
{
break;
}
// do something with var
}
printf("Job done!");
return 0;
}
I have a simple console program written in C and want to abort a text input with CTRL + Z. How is it possible?
Edit: Here is some code (untested).
#include <stdio.h>
int main()
{
float var;
while(1)
{
scanf("%lf", &var); // enter a float or press CTRL+Z
if( ??? ) // if CTRL+Z was pressed
{
break;
}
// do something with var
}
printf("Job done!");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
基本上是这样的:
如果在行中间按 Ctrl+Z 可能会出现复杂情况,但从基本开始。
OP 更新后编辑
您有
scanf
返回它所做的分配数量。在您的情况下,您只有 1 个变量,因此scanf
在正常情况下返回 1,在失败时返回 0。只需检查返回值PS:哦... scanf 中的说明符“%lf”需要一个
double
,你程序中的var
是一个float
>。也纠正一下Basically like this:
There may be complications if you press Ctrl+Z in the middle of the line, but start with the basic.
Edit after OP was updated
You have
scanf
returns the number of assignments it did. In your case, you only have 1 variable, soscanf
returns 1 in the normal case or 0 when it fails. Just check the return valuePS: Oh ... the specifier "%lf" in scanf requires a
double
,var
in your program is afloat
. Correct that too使用 signal.h 来帮助捕获当您按下 Ctrl+z 时发送的
SIGTSTP
。请注意,您需要捕获 SIGTSTP 而不是 SIGSTOP,因为暂停是 SIGSTOP 的必需操作,而仅是 SIGTSTP 的默认操作。您还可能会遇到信号生成时
scanf()
没有返回的问题。幸运的是,这个问题已经被提出并得到了很好的回答:) Scanf with Signalsuse signal.h to help trap the
SIGTSTP
sent when you hit Ctrl+z. Note that you'll want to catch SIGTSTP and not SIGSTOP as pausing is a required action for SIGSTOP by only the default action for SIGTSTP.You may also run into problems not having
scanf()
return when the signal is generated. Luckily for you, that question has been asked and answered quite nicely already :) Scanf with Signals如果您使用的是类 UNIX 操作系统,则 ctrl-z 会发送 SIGSTOP,您可以通过编程方式生成该信号,并使用 sigaction 捕获该信号。
If you're using a UNIX-like operating system, ctrl-z sends a SIGSTOP, which you can generate programmatically, and catch with sigaction.