0

This has probably been answered somewhere, I just can seem to find an answer to it. Anyways, I am making a program that loops a certain number for times, however I would like the program to take the input of the user after they have hit a space bar to trigger the fact the user will be inputting something. Now my logic maybe off but this is what I am trying.

  for ( int i = 0 ; i < length (user input from before); i++){
     do{
        cout << "Hello World" << endl;
     }while(cin.getch() == ' ');
  }

From what I see the program doing, it stops each time my iterator is increased. I'm kinda sure the logic on why it's stopping each time but how do I make it so it loops and only stops when the user hits the space key?

5
  • Put the getCh() into its own thread. Then enjoy the added complexity :) Way back when you could use DOS interrupt 9 and a callback. Now, I think that this is the best way. Commented Nov 13, 2017 at 21:53
  • @Michael Dorgan im going to be a little honest and ask what you mean by placing it into its own thread? Commented Nov 13, 2017 at 21:57
  • Here's a better answer: stackoverflow.com/questions/6171132/… Commented Nov 13, 2017 at 22:00
  • The key was googling for "C++ nonblocking input" Commented Nov 13, 2017 at 22:00
  • getch is not a member of class istream. Maybe you meant cin.get(). Commented Nov 13, 2017 at 22:12

1 Answer 1

1

getch is a blocking function, i.e if the input buffer is empty, it blocks the current thread and waits for user input. If you like to have something working in the meanwhile, you'd have to spawn a separate thread. See the following code that starts a new thread for the "worker", while the main thread waits for user input. Hope it helps somehow.

#include <iostream>
#include <thread>

struct Worker {
    Worker() : stopped(false) {};
    void doWork() {
        while (!stopped) {
            cout << "Hello World!" << endl;
        }
        cout << "Stopped!" << endl;
    }
    atomic<bool> stopped;

};

int main(){

    Worker w;
    thread thread1(&Worker::doWork,&w);

    int c;
    while ((c = getchar()) != ' ');

    w.stopped = true;

    thread1.join();  // avoid that main thread ends before the worker thread.
}
Sign up to request clarification or add additional context in comments.

2 Comments

this may be wrong or insignificant but isn't "struct" a C thing not C++? I was tough in C++ to use classes?
@eM3e: C++ provides botch classes and structs. A struct in C++ has almost the same meaning as a class; the sole difference is that - by default - every member is public.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.