Is there a way to use _getch() in the repetition sentence in C language so that it repeats even when there is no input?

Asked 2 years ago, Updated 2 years ago, 61 views

It's supposed to be 1 every second from 0 and if you type r, it starts from 0 again I was going to end the program by typing q. I made it as below, but it works only when I keep pressing other buttons on the keyboard. In this case, please advise how to use it.

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <windows.h>

int main(void)
{
    int n = 0;

    while (1)
    {
        system("cls");
        printf("%d\n", n);
        printf("r : count initialization q : program termination\n");
        n++;
        Sleep(1000);
        if (_getch() == 'q')
            break;
        else if (_getch() == 'r')
            n = 0;
    }

    return 0;
}

c loops

2022-09-22 16:46

1 Answers

The main() function is executed when the program written by Horizon is executed This function is executed from top to bottom with one execution flow in the main process.

As you run from top to bottom, the main process meets the _getch() function It's like a function that takes input, but it's usually a function that you get input from the user It stops the main process and waits for the user to complete the input So the printout stops at the same time, because the main process stops

The solution is to make two execution flows, one of which outputs a number that grows over time, and the other of which waits for user input and then takes action when it receives input.

Search for and recreate the thread Fighting


2022-09-22 16:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.