How to make the program work, say a cycle, but wait for the input information? Suppose we have an infinite loop that lists the numbers in ascending order. It works and turns the numbers endlessly until the moment when the user writes a stop. How to do it and is it possible in a console application?

  • while(true){ cin >> s; do_smth();} while(true){ cin >> s; do_smth();} go? - pavel
  • one
    cin stops the program and waits for input. I need the program to work and wait for input at the same time. - Nick Frankin
  • one
    multithreading? - MSDN.WhiteKnight
  • one
    No, this is not what I need - Nick Frankin
  • I'm not sure that a portable solution is possible, a similar question on the main SO - Non-blocking console input C ++ - user227465

1 answer 1

Good. This solution displays the numbers until any key on the keyboard is pressed. In this problem, the kbhit() method is very useful.

 #include <iostream> #include <conio.h> using namespace std; int main() { bool run = true; while (run) { for (int i = 1; i<1000000; i++) { if (kbhit()) { run = false; break; } cout << i << "\n"; } } system("pause"); return 0; } 

If it is necessary for you that the user enter exactly the word "stop", then my decision, unfortunately, is absolutely not for you ...

  • 2
    If anything, this is not a portable solution ... - Fat-Zer
  • so, the code works as it should, so much more convenient. Thank you for any solution of the problem, I will dig deeper, create commands like "stop". But you gave a good start, now I at least know that the solution exists. Thanks again - Nick Frankin