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开发者_Go百科 or press CTRL+Z
if( ??? ) // if CTRL+Z was pressed
{
break;
}
// do something with var
}
printf("Job done!");
return 0;
}
Basically like this:
if (fgets(buf, sizeof buf, stdin)) {
/* process valid input */
} else {
/* Ctrl+Z pressed */
}
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("%lf", &var);
scanf
returns the number of assignments it did. In your case, you only have 1 variable, so scanf
returns 1 in the normal case or 0 when it fails. Just check the return value
int n = scanf("%lf", &var);
/* test the return value of scanf: 1 all ok; 0 no conversions; EOF: error/failure */
if (n != 1)
{
break;
}
PS: Oh ... the specifier "%lf" in scanf requires a double
, var
in your program is a float
. Correct that too
use 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
If you're using a UNIX-like operating system, ctrl-z sends a SIGSTOP, which you can generate programmatically, and catch with sigaction.
精彩评论