By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,412 Members | 996 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,412 IT Pros & Developers. It's quick & easy.

Input without pressing Enter

P: n/a
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
Jul 19 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On 4 Aug 2003 07:48:34 -0700, wh*****@maths.warwick.ac.uk (paul)
wrote:
Have read the FAQ's
Are you sure?

http://www.parashift.com/c++-faq-lit...html#faq-15.17
computes something or other and have the ability to detect when a key
is pressed to make the program output its current reults.

Jonathan

Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.