-2

i wanted to create a snake program in console application. but in one where i confused. my problem like this:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <conio.h>
using namespace std;
int main() {
    int a=2000;
    while (1) {
        cout << time(0)<<endl;
        a -= 100;
        _sleep(a);
      **if (getch())break;
        else continue;
    }
}

my problem in **, i want from it ,to do that while loop until i pressed one key. for example i want from it run like this: print time(). a = 1900. wait 1.9s. print time(). a=1800. wait 1.8 s. // now i pressed a key. break.//end program

so i found answer i used kbhit() in conio.h library.

Ali
  • 1
  • 2
  • You will need to use platform specific API to determine when a key was pressed or released. The standard C++ language has no facilities for key presses. The C++ input functions *block* or wait at least until a character has arrived; some may wait for many characters are typed before acting upon them (such as pressing the Enter key). – Thomas Matthews Apr 14 '17 at 20:07
  • Also, search the internet for "StackOverflow C++ snake game console" to see a plethora of similar questions. – Thomas Matthews Apr 14 '17 at 20:08

1 Answers1

0

You may try this. Of course you need to do something in the parent process to have getchar() return for any key press without waiting, such as using _getchar().

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <signal.h>
#include <conio.h>
using namespace std;
int main() {
    pid_t id;
    id = fork();
    if(id)
    {
      getchar();
      kill(id, SIGTERM);
    }
    else
    {
        int a=2000;
        while (1) {
            cout << time(0)<<endl;
            a -= 100;
            _sleep(a);
          /*if (getch())break;
            else continue;
            */
        }
    }
}
Shiping
  • 1,203
  • 2
  • 11
  • 21