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

質問

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.

役に立ちましたか?

解決

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..

他のヒント

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top