Have Loop Running and Receiving User Input

Hello, I have been programming in C++ for about 3 weeks now, and I have an idea for a project but I have come to a halt. I would like to know if it possible to have a loop running while also being able to detect when a user presses a key.
Output Example

"Loop Is Running
Loop Is Running
Loop Is Running
Loop Is Running
The User Pressed a Key!
Loop Is Running
Loop Is Running
Loop Is Running
Loop Is Running"

I have tried using the threads from C++11 but the program just comes to a halt as it always does with input functions (I am using getche() so that the user does not have to press enter)
Is there any way (Hopefully simple) that I can accomplish this?
TIA
Last edited on
make a loop inside a thread, and let it run the loop.
when key is pressed interrupt the thread.

the thread will die and terminate the loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <string>
#include <iostream>
#include <boost/thread.hpp>

void my_thread()
{
        try
        {
	      while (true)
	      {
                     // run loop
                     std::cout << "Loop is running" std::endl;
	      }
         }
        catch (const boost::thread_interrupted& e)
	{
		std::cout << "loop interrupted" << std::endl;
	}

}

int main()
{
	boost::thread thread(my_thread);

        std::string info;

try_again:
        std::cin >> info;

	if (info == "terminate")
                thread.interrupt();
        else goto try_again;

        // thread.join();
        return 0;
}
Last edited on
The code from above should work out, just try to avoid using goto! Goto is not unnecessarily called spaghetti code! It is very messy and will eventually slatter the sauce upon you ;)
Last edited on
Topic archived. No new replies allowed.