Search code examples
cwhile-loopgetchar

Repeat until user presses enter


I want to have a loop, that repeats until the user presses enter.

I tried with while(getchar != '\n'){} but this waitet on a input every single time. Right now i dont know how to do this.

do {
        clear;//system("cls");
        printf("\nPress [enter] to continue");
        printf(".");
        Sleep(500);
        printf(".");//should give a output with press enter to continue... and wait after every point.
        Sleep(500);
        printf(".");
        Sleep(500);
    }while(getchar() != '\n');

Solution

  • the following code is from kbhit for linux

    #include <stdio.h>
    #include <termios.h>
    #include <unistd.h>
    #include <fcntl.h>
    
    int kbhit(void)
    {
      struct termios oldt, newt;
      int ch;
      int oldf;
    
      tcgetattr(STDIN_FILENO, &oldt);
      newt = oldt;
      newt.c_lflag &= ~(ICANON | ECHO);
      tcsetattr(STDIN_FILENO, TCSANOW, &newt);
      oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
      fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
    
      ch = getchar();
    
      tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
      fcntl(STDIN_FILENO, F_SETFL, oldf);
    
      if(ch != EOF)
      {
        ungetc(ch, stdin);
        return 1;
      }
    
      return 0;
    }
    
    int main(void)
    {
      while(!kbhit())
        puts("Press a key!");
      printf("You pressed '%c'!\n", getchar());
      return 0;
    }