0

Eg:

cout<<"\n Time used (in seconds) :";
for(int i=0; i<100; i++)
{
       cout<< i;
       delay(1000);
       cout<<"\b"; 
}

I want to modify the program segment so that while the loop goes on, if user presses any key (during run time), the loop stops. If he does not, the loop continues normally till i=100.

I realize multithreading is the only to do this. Since I am a beginner, I'd like if you tell me how to go about it without using classes. Please give me a program with comments to explain the syntax and logic.

  • Basically you wants unblocking behavior of `cin` or `select()` kind of function. Read [Non-blocking call for reading descriptor](http://stackoverflow.com/questions/5616092/non-blocking-call-for-reading-descriptor) **or** [using fgets as non-blocking function c++](http://stackoverflow.com/questions/6055702/using-fgets-as-non-blocking-function-c) **or** [Non-blocking console input C++](http://stackoverflow.com/questions/6171132/non-blocking-console-input-c) – Grijesh Chauhan Jan 20 '14 at 15:06
  • 5
    "Please give me a program" doesn't go over so well! – Lightness Races in Orbit Jan 20 '14 at 15:11

1 Answers1

1

Windows provides extensive documentation on threading, see the following tutorial on how to create threads in C++: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682516%28v=vs.85%29.aspx

Alternatively you could use the boost libraries which will work on most modern operating systems, including UNIX and Windows, here is a tutorial for that: http://antonym.org/2009/05/threading-with-boost---part-i-creating-threads.html

You should also look into a more accurate method of timing, I found this thread on StackOverflow discussing timing: How to Calculate Execution Time of a Code Snippet in C++

Community
  • 1
  • 1
jProg2015
  • 1,098
  • 10
  • 40