Is it possible to exit a C console application without threads at any time by pressing a key? [duplicate]

StackOverflow https://stackoverflow.com/questions/21166561

Pergunta

Let's suppose I'm in a while (1) loop calculating something, would it be possible to quit the whole application by pressing a certain key?

It's a C console application without threads.

I'm pretty sure it's not possible, but I'm a newbie so hey. I can only imagine beeing forced to press a key by some function like _getch() or similar. But then you have to wait until the user presses the key and the calculation cannot run meanwhile.

Foi útil?

Solução

On Windows systems, there's kbhit() function that is nonblocking and returns true when any key is pressed. So, you could change while(1) to while(!kbhit()), or you could if(kbhit()) c = getch() to read the char without waiting. But this is very crude solution, really..

Outras dicas

You could do that by using C "signals".

This is not really difficult to use. Take a look at this wikipedia page. ;)

http://en.wikipedia.org/wiki/C_signal_handling

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top