I am new to c++ programming and please forgive me if I made silly mistakes.
In real world scenario we would always have an emergency exit/stop button if some thing goes wrong in a process. I also want to simulate similar emergency exit code in c++ command line.
I have used this stackoverflow.com/a/5845305/996366 code for writing my code.
#include <iostream>
#include <unistd.h>
unsignedint microseconds;
int main()
{
int i=0;
int input;
std::cout<<"please enter 911 to exit loop: ";
while (std::cin.good())
{
int input;
input = std::cin.peek();
if( input == 911 )
{
break;
}
else
{
std::cout<<i<<"\n";
i=i+1;
}
usleep(microseconds);
}
return 0;
}
unless other vise 911 (a validation integer) is inputed by the user the code should print increment value of i in infinite loop. Some where in the code I made a logical error which caused improper working of the code?
Are you trying to achieve non-blocking console I/O (i.e. detecting individual keystrokes)? This is not possible using functions from the standard library.
The problem with above code is I have to manually enter number on every loop. What I want is , I want to exit a loop which is already active when an user input 911.
real world problem
Lets assume I am using loop function for downloading some files from thousands of url and lets say in the middle of the looping I noticed some thing and want to halt the looping in the middle. The easiest way would be to close the program itself but I am looking for a programmatic way to exit the loop by validating from a user input(911/EXITPROG..etc)
Yes, that would require non-blocking I/O. Like I said, that's not possible with iostreams.
It's possible to detect when the user hits Ctrl+C and perform a clean shutdown (i.e. stop loop, call destructors, etc.) instead of an instant termination. I've done this a few times because properly doing what you're trying to do is overkill in most situations. To do this, you use signal() to override the handler for SIGTERM. In the handler, you flip a bool (note that the handler may be run in a different thread than main()) that you check in the main loop. When the bool changes to the signaled state, you break out and exit.
If you still want to do it with actual keystrokes, you'll need to use one of the curses libraries.