Stopping an Infinite Loop in C++ When Key Is Pressed

C exit from infinite loop on keypress

I would suggest that you go throgh this article.

Non-blocking user input in loop without ncurses.

stop infinite loop or process with press a specific key in c

Hy man you can do something like this:

#include <stdio.h>
#include <conio.h> // include the library header, not a standard library

int main(void)
{
int c = 0;
while(c != 'key that you want') // until correct key is pressed
{
do {
//Fibonacci sequence
} while(!kbhit()); // until a key press detected
c = getch(); // fetch that key press
}
return 0;
}

Infinite loop till key pressed

This is a little different, to show you a simple solution. But if you are not allowed to use kbhit you are stuck.

#include <stdio.h>
#include <conio.h> // include the library header

int main(void) // correct signature for main
{
int c = 0; // note getch() returns `int` type
while(c != 'n') // until correct key is pressed
{
do { // forever
printf("Hello\n");
} while(!kbhit()); // until a key press detected
c = getch(); // fetch that key press
}
return 0;
}

Remember, it only tests for lower-case n.

C++: How can I make an infinite loop stop when pressing any key?

Use system signal but you will not be able to stop with all keys.

#include <iostream>
#include <csignal>

using namespace std;

void signalHandler( int signum )
{
cout << "Interrupt signal (" << signum << ") received.\n";

// cleanup and close up stuff here
// terminate program

exit(signum);

}

int main ()
{
// register signal SIGINT and signal handler
signal(SIGINT, signalHandler);

while(1){
cout << "Going to sleep...." << endl;
sleep(1);
}

return 0;
}

How to stop infinite loop when character is pressed in place of int?

Add this after the scanf()

char ch;

while( ( ch = getchar() ) != '\n' && ch != EOF );

This should do the trick.

The problem was caused as scanf() does not store characters ( since you are using %d ) and thus they remain in the input buffer. The next scanf() tries to read this and again, instead of storing it, ignores it and it remains in the buffer. This process repeats, which causes the infinite loop.

The code I gave reads all the characters in the buffer, thus reomoving the infinite loop.

Cheers... Hope this helps you :)

Implementing a Press any key to stop refreshing loop in Python

Using Ctrl+C is fine, but you should use exception handling. Catch KeyboardInterrupt, and use finally to define cleanup actions.

def run():
my_object = MyClass()
my_object.lay_the_table()
print("Telling my_object to keep refreshing... Use Ctrl-C to stop.")
try:
while True:
my_object.refresh()
except KeyboardInterrupt:
pass
finally:
my_object.tidy_away()

if __name__ == "__main__":
run()

Since Ctrl+C sends an interrupt, this is actually probably the easiest way to do it.



Related Topics



Leave a reply



Submit