Sending ctrl + z to the console program

I have a simple console program written in C and you want to interrupt text input with CTRL+ Z. How is this possible?

Edit: Here is the 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;
}
+3
source share
3 answers

Mostly like this:

if (fgets(buf, sizeof buf, stdin)) {
    /* process valid input */
} else {
    /* Ctrl+Z pressed */
}

You may have difficulty if you press Ctrl + Z in the middle of the line, but start with the main one.


Change after upgrade OP

You have

scanf("%lf", &var);

scanfreturns the number of appointments he made. In your case, you only have one variable, so it scanfreturns 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: ... "% lf" scanf double, var float.

+1

signal.h, SIGTSTP, Ctrl + z. , SIGTSTP, SIGSTOP, SIGSTOP SIGTSTP.

, scanf() . , :) Scanf with Signals

+1

UNIX- , ctrl-z SIGSTOP, , sigaction.

0

Source: https://habr.com/ru/post/1770561/


All Articles