user1319951
user1319951

Reputation: 505

Doing operations in a while loop until a key combination is invoked c++

I have the following issue. I want to do some certain operations in a Linux terminal until the key combination CTRL+D is invoked. I have found a C++ library function for Windows that can do this, but no easy solution for Linux. The code skeleton will be something like this:

while(!invoked){ //Until CTRL+D is pressed
//Do something
}
//Continue when CTRL+D is invoked

Is this possible?

Upvotes: 0

Views: 338

Answers (3)

piokuc
piokuc

Reputation: 26194

Use getch from (n)curses library. As zaufi already explained, checking for EOF while reading from standard input, with, e.g. getchar, is like checking for Ctrl-D, but it's a blocking operation. getch is non-blocking (in nodelay mode), so more suitable for things like, for example, games.

Upvotes: 0

Giuseppe Pes
Giuseppe Pes

Reputation: 7912

This interrupts the cycle when the combination `CRTL + D' is inserted :

while ((c = getchar()) != EOF)

Note in Linux is CRTL-D stands for EOF. It is the equivalent of CTRL-Z in windows.

Upvotes: 2

zaufi
zaufi

Reputation: 7129

the easiest way to wait for Ctrl+D is to read smth from std::cin and then check for EOF in a stream. the problem is: this call would block. so doing smth should occur in some other thread. then, you have to signal (via conditional variable for example) to that worker thread from the waiter...

Upvotes: 1

Related Questions