Question

So i need to write an whileloop for a program that's supposed to prompt the user with this:

char vector[10];
while(????){
    print("Write a number");
    scanf("%s",vector);
}

printf("Goodbye");

The program is supposed to print goodbye and close when the user presses ctrl+c. Im pretty sure I cant use putchar in this case?

Était-ce utile?

La solution

#include <windows.h>
#include <stdio.h>

static end_flag = 0;

BOOL WINAPI controlHandler(DWORD type){
    if(type == CTRL_C_EVENT){
        end_flag = 1;
        return TRUE;
    }
    return FALSE;
}

int main(){
    char vector[10];

    if (!SetConsoleCtrlHandler(controlHandler, TRUE)) {
        fprintf(stderr, "Failed SetConsoleCtrlHandler");
        return -1;
    }
    while(!end_flag){
        printf("Write a number ");
        scanf("%s",vector);
    }

    printf("Goodbye");
    return 0;
}

CTRL+Z version

#include <stdio.h>

int main(){
    char vector[10];

    while(1){
        printf("Write a number ");
        if(scanf("%s", vector)==EOF)//press CTRL+Z
            break;
    }

    printf("Goodbye");
    return 0;
}

Autres conseils

see https://superuser.com/questions/214239/whats-the-command-prompts-equivalent-to-cygwins-ctrlz:

Depends on what you mean by "quit something"; within Windows cmd:

Ctrl+Z sends the EOF character, which could terminate a process if you're providing input, but otherwise will probably do nothing.

Ctrl+C normally sends SIGINT to the foreground process, which should terminate it, but programs can respond however they like - ie, they can catch the signal but then ignore it. The command can also be remapped to other jobs (such that for a specific program it doesn't really send a signal) or ignored entirely.

Ctrl+Break always sends SIGBREAK, which again should terminate the process, but unlike Ctrl+C cannot be remapped, but can still be ignored. This is probably what you need.

Post similar to this one on Stack Overflow: Catch Ctrl-C in C

You might want to check it out. Cheers!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top