-1

I am working on a simple code that keeps incrementing a counter every second and will stop incrementing only when a 'q' is pressed .

I tried getchar() and getline() , but they require the user to enter an input for every loop .

to make it simpler , this code keeps counting on the console forever until I terminate it by ( Ctrl+c ) , I would like to use 'q' to do the same functionality.

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int j=0;
int main()
{
    printf("Enter Q to quit !\n");
    while(1)
    {
    j++;
    printf("%d\n",j);
    Sleep(1000);
    system("cls");
    }
    return 0;

}
Omar Hussein
  • 39
  • 1
  • 9

2 Answers2

1

The fact that you include windows.h makes me think you're looking for the kbhit() function. From the linked page:

This function is not defined as part of the ANSI C/C++ standard. It is generally used by Borland's family of compilers. It returns a non-zero integer if a key is in the keyboard buffer. It will not wait for a key to be pressed.

On UNIX/Linux, you have to resort to terminal mode manipulation as described in the answer linked by @i_am_jorf.

Community
  • 1
  • 1
evadeflow
  • 4,704
  • 38
  • 51
1

I see you are using Windows, so MSVC has kbhit() or _kbhit() to detect a key press, after which you call getch() or _getch() to get that keypress.

#include <conio.h>
#include <stdio.h>
#include <windows.h>

int main()
{
    int j=0;
    printf("Enter Q to quit !\n");
    do {
        j++;
        printf("%d\n",j);
        Sleep(1000);
    } while (kbhit() == 0 || getch() != 'Q');
    return 0;
}

Why does the while not block on getch? Because of short circuit evaluation. If kbhit == 0 is true, then getch() != 'Q' is not evaluated.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56