0

I am going to write a program in which there is a while loop in which the user can input the program at any time, but the while loop does not wait to receive the user input and continues to work. Whenever a user enters a new input, the program will run according to that input. The program is in C ++ and the name of the program is Snake Game. I'm sorry because my code is too long, I can show a small part of it.

while(1)
{

    Move(grid,snake,grid_rows,grid_cols,len_snake,ch);
    show(grid,grid_rows,grid_cols);

    Sleep(1000);
    cin>>ch;
    system("CLS");
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 5
    Using standard C++ all input operations on `std::cin` will be *blocking* until the terminal decides to actually send something to your program. You need to use OS-specific functionality for non-blocking terminal input. – Some programmer dude Oct 04 '21 at 06:19
  • Mby you're looking for a thread functionality? – Sule Oct 04 '21 at 06:20
  • If it can get me to my goal – mohamadmahdi Oct 04 '21 at 06:25
  • 2
    Have a look at this : https://stackoverflow.com/questions/29335758/using-kbhit-and-getch-on-linux, @Sule That might unecessarily complicate things at this moment. – Pepijn Kramer Oct 04 '21 at 06:29
  • 3
    @Sule - Threading doesn't cover it. If blocking I/O is used on one thread that is waiting for user input (from terminal, keyboard, or whatever) then that thread will be blocked. So user input doesn't work well in practice if more than one thread is trying to capture user input. What's needed is non-blocking input (e.g. an input operation immediately returns if there is no pending input - usually with an indication that it has done so) and the C++ standard specifies no such a thing. So as already noted, OS-specific functionality (or some library that wraps such functionality) is needed. – Peter Oct 04 '21 at 06:29
  • FYI: [SO: I/O in concurrent program](https://stackoverflow.com/a/48097134/7478597). – Scheff's Cat Oct 04 '21 at 07:54

1 Answers1

0

thank you pepijn kramer.With your help, I completed my program.

    while (1)
    {
    system("CLS");
    show(grid,grid_rows,grid_cols);


    if (_kbhit())
    {
        ch = _getch();
    }

    Move(grid,snake,grid_rows,grid_cols,len_snake,ch);

    check_(grid,snake,grid_rows,grid_cols,len_snake);

   Sleep(500);
}
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 05 '21 at 05:21