how to break out infinite loop?
I want to know in the infinite loop, how to keep track if user hit any key especially ESC key then break out of infinite loop.
Here is my code:
for (;;)
{
// please help me to figure it out this section here how to keep track if user hit any key
// waiting user to hit any key
// if user hit ESC key then break;
// otherwise
.... my tasks.....
..................
}
Re: how to break out infinite loop?
1. Set a member variable to false before entering your loop.
2. When you enter the loop, set a flag variable to show you're in the loop, and upon exiting the loop, reset the flag variable.
3. Use ClassWizard to set up a PreTranslateMessage() handler.
3. In the PreTranslateMessage(0 handler, look for key down. If the key is escape, and you're in your loop, set the member variable mentioned in step 1 to true.
Sample code:
// in your class header file
bool m_bBreak; // will be true when loop needs to stop
bool m_bInLoop; // only true when inside our loop
// PreTranslateMessage() handler in your implementation file:
BOOL CMyClass::PreTranslateMessage(MSG* pMsg)
{
if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_ESCAPE && m_bInLoop)
m_bBreak = true;
return CDialog::PreTranslateMessage(pMsg);
}
// your loop:
m_bBreak = false;
m_bInLoop = true;
while(!m_bBreak)
{
// Do your loop processing here.
// When user hits the escape key, the handler will set m_bBreak to true,
// causing your loop to exit
}
m_bInLoop = false;
Re: how to break out infinite loop?
Well you have written it already...
for(;;){
if( need to break )
break;
}
the break; will break out of the loop you are in, if you are in nested loops, it will break out of the inner and continue in the outer loop. A not very nice one but effective with many nested loops is to set a label and use goto.
Regards Albert Bertilsson
http://www.albert.nu
Re: how to break out infinite loop?
I think I've answered this type of question half-a-dozen times. Here's a link to one of them:
http://www.codeguru.com/bbs/wt/showp...age=0&Limit=25
Regards,
Alvaro
Re: how to break out infinite loop?
If the while loop processing is done as a result of some input message, like a mouse click or key stroke then the call to PreTranslateMessage likely won't happen until the looping returns. I think you need to look closer at multi threading this.
HTH.
Re: how to break out infinite loop?
An easy way to do this is
for (;;)
{
//do your stuff
if (GetAsyncKeyState(VK_ESCAPE)<0) break;
}
So you don't have to use the pretranslates/messagepumps/threads
Hope this helps,
Steven
Re: how to break out infinite loop?
#include <conio.h>
for(...)
{
if(kbhit())
{
DestroyWindow();
}
}
or just put it into the OnKeyDown function
for(...)
{
if(nChar == VK_ESCAPE)
{
DestroyWindow();
}
}