-1

I wrote a for loop that prints a dynamic array. Thus, when sizes of array are too big, the loop prints too many lines. So, how can I break the loop whenever I press a specific key?

Here is my code:

for(int x = 0; x < lineCombCount; x++){
    for(int y = 0; y < dirCombCount; y++)
    {
        combRowNum++;
        cout << combRowNum << " >> ";
        for(int z = 0; z < allLineNumber; z++)
        {
            cout << arryLine[x][z] + arryDir[y][z] << " ";
        }
    
        cout << endl;
    }
}
Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696
  • 3
    Which platform are you targetting? C++ has no standard way to detect a keyboard press asynchronously, so you will have to resort to platform-specific methods. Or, you could simply run the loop in a separate thread, and have the main thread wait on `cin.get()` in a loop, and then terminate the worker thread when the desired key is entered. – Remy Lebeau May 26 '22 at 18:01
  • 1
    Just about every operating system and many third-party console support libraries will provide a more direct, non-blocking way to check for input allowing you to place the check for input inside the loop. Simpler, probably less overhead, and usually faster, but The problem here is your program may not be as portable as you'd like. – user4581301 May 26 '22 at 18:07

1 Answers1

0

Hope this helps:

#include <unistd.h>
#include <iostream>
#include <cstdlib>
#include <signal.h>
using namespace std;
// Define the function to be called when ctrl-c (SIGINT) is sent to process
bool isInterrupted = false;
void signal_callback_handler(int signum) {
   cout << "Caught signal " << signum << endl;
   isInterrupted=true;
   //exit(signum);
}
int main(){
   // Register signal and signal handler
   signal(SIGINT, signal_callback_handler);
   while(!isInterrupted){
      cout << "Program processing..." << endl;
      sleep(1);
   }
   cout << "Program interrupted with ctrl + c" << endl;
   return EXIT_SUCCESS;
}

Output:

╰$ ./a.out
Program processing...
Program processing...
Program processing...
^CCaught signal 2
Program interrupted with ctrl + c

To understand more: https://www.tutorialspoint.com/how-do-i-catch-a-ctrlplusc-event-in-cplusplus

Better one: Non-blocking console input C++

H.K
  • 66
  • 3
  • 3
    The operations which are guaranteed to work in a signal handler are very restricted. In particular `isInterrupted` must be a lock-free atomic. Especially if it is not atomic at all, the compiler might just optimize the loop check away. Output functions like `cout < – user17732522 May 26 '22 at 18:23
  • @user17732522 Agreed also thanks for a great insight - learnt something new! I just tried to show options if works for him. – H.K May 26 '22 at 18:53