Input without pressing Enter

P

paul

Have read the FAQ's and the forums but still cant find a good solution
to this. I am using Linux and G++. I am trying to run a program which
computes something or other and have the ability to detect when a key
is pressed to make the program output its current reults. I.e. The
main iteration runs continuously the user can press 'o' say at any
time to output what it has.

At the moment I am looking at using a separate thread to handle the
key pressing and use this to change a global variable which is checked
roughly every minute (the program will run for about 24hrs). If there
is a different better way to do this would like to know. Here is what
I have so far:

#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <iomanip.h>
#include <stdio.h>


int printnext;

void *thread_function(void *arg) {
char ch;
while(printnext==0) {
cin.get(ch);
cout << "pressed " << ch << endl;
if (ch == 'q' || ch=='Q') {
printnext=1;
}
}
return NULL;
}

int main(void) {

printnext = 0;

pthread_t mythread;

if ( pthread_create( &mythread, NULL, thread_function, NULL) ) {
cout << "error creating thread." << endl;
abort();
}

for (int i=0; i<100000; i++) {
if (printnext==1) {
cout << "Pressed something" << endl;
break;
printnext=0;
}
sleep(1);
}

if ( pthread_join ( mythread, NULL ) ) {
cout << "error joining thread." << endl;
abort();
}

exit(0);

}

This works well but however the user has to press enter after q, this
is what i dont want. I want to be able to just press q. Have tried
putting in ncurses and using getch but it produces segmentation
errors. Have no idea why. At the moment it is compiled with g++
test.cpp -lpthread. Any help on this would be greatly appreaciated.
Thanks
Paul
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top