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?

eM3e
  • 45
  • 7

1 Answers1

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.
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
  • this may be wrong or insignificant but isn't "struct" a C thing not C++? I was tough in C++ to use classes? – eM3e Nov 13 '17 at 22:19
  • @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. – Stephan Lechner Nov 13 '17 at 22:21