0

I am writing a Win32 GUI app which has a loop which I would like to restart only when a keypress is made. The main loop is already running, and I can't simply restart it, so I have to insert a 'hang' point which the user can manually break out of. The code below represents what I have put at the end of my main loop. It is supposed to pause the program by putting it into an endless sub-loop which can only be broken when the letter 'q' is pressed.

for (;;)
 {
 char temp;
 temp = _getch();

 if (temp == 'q')
  {
  break;
  }
 }

This successfully makes the program hang, but pressing 'q' does nothing to end the loop. I understand that using cin.ignore() or cin.get() would be preferable, but for some reason when I add iostream to the header list, I get a bunch of errors, so I am currently trying to do it using _getch() with the conio.h header.

Any help much appreciated.

CaptainProg
  • 5,610
  • 23
  • 71
  • 116

4 Answers4

2

You can just call MessageBox.

oɔɯǝɹ
  • 7,219
  • 7
  • 58
  • 69
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
1

It's hard to tell from your question, but it sounds like you're trying to prompt the user after each iteration of a loop if they wish to continue. I assume that the infinite for loop is at the end of your main processing loop.

You don't need the infinite loop: _getch() will halt execution anyway until a key is pressed. In truth, the fact that you've wrapped your conditional in a for loop is the reason that break isn't behaving like you want -- you're breaking out of the infinite loop, but not your main processing loop.

Example:

while(1)
{
   // Do some processing
   for (;;)
   {
      char temp;
      temp = _getch();

      if (temp == 'q')
         break;   // This will break out of the for and continue the while
   }
}

vs.

while(1)
{
   // Do some processing
   if ('q' == _getch())
      break;             // This will break out of the while
}

You'll also notice that since _getch() returns a char, you can just test the return code of the function (unless you need to store the input for later use).

Justin ᚅᚔᚈᚄᚒᚔ
  • 15,081
  • 7
  • 52
  • 64
0

You have to create a message loop and wait until a keydown message arrives. Try to check this example.

In a windows GUI application there is no input to read from the console.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
0

You mentioned this is a Win32 GUI application. At the time of entering the loop, have you created any Windows that might have the input focus? if yes you should try trapping WM_KEYDOWN/WM_KEYUP messages. If it is a console application, look at Console Functions specially ReadConsole.

Sam

Sam
  • 2,473
  • 3
  • 18
  • 29