Input without pressing Enter

Discussion in 'C++' started by paul, Aug 4, 2003.

  1. paul

    paul Guest

    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
     
    paul, Aug 4, 2003
    #1
    1. Advertising

  2. Jonathan Mcdougall, Aug 4, 2003
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jerry
    Replies:
    4
    Views:
    1,182
    John Saunders
    Jul 25, 2003
  2. LaBird

    Input without pressing enter?

    LaBird, Oct 16, 2003, in forum: C Programming
    Replies:
    6
    Views:
    1,205
    Joona I Palaste
    Oct 16, 2003
  3. unni.tallman
    Replies:
    3
    Views:
    1,642
    Fredrik Lundh
    Sep 20, 2006
  4. bhutho
    Replies:
    3
    Views:
    589
    Turma 15 FCM
    Oct 28, 2011
  5. unni.tallman
    Replies:
    3
    Views:
    206
    James Edward Gray II
    Sep 20, 2006
Loading...

Share This Page