简体   繁体   中英

Is there a function that interrupts loop in C programming?

I have this program in C that displays the letter "o" for 2 seconds if the letter "t" or "d" is pressed and stops with the letter "O", the same thing if the letter "i" is pressed but ends with the letter "C". I want to find out if is there a function or something that while those 2 seconds pass if I press the letter "t" stops and shows me the letter "S" and if I press it again continues with the letter "o" and the same thing if I press the letter "i" while the "c" sequence is running.

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

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

void wait(long milliseconds)
{
long timeout = clock() + milliseconds;
while (clock() < timeout) continue;
}

int main() {
int key = 0;
int i=0;
int count = 5;

while (1)
{
    if (_kbhit())
    {
        key = _getch();

        if (key == 'i')
        {

            time_t secs = 120;
            time_t startTime = time(NULL);
            while (time(NULL) - startTime < 2)
            {
            printf("c");
            Sleep(200);
                
            }
            printf("C");

        }

          if (key == 'd' || key == 't')
        {
            time_t secs = 120;

            time_t startTime = time(NULL);
            while (time(NULL) - startTime < 2)
            {
                printf("o");
                Sleep(200);
            }
            printf("O");
        }
       
    }
}
return 0;
}

It's a little bit unclear what you're looking for, but this piece of code will roughly do what you want:

while (time(NULL) - startTime < 2)
{
    char ch = 'o';

    if(_kbhit()) {
        int x = _getch();
        if(x == 't') 
            ch = ch == 'c' ? 'S' : 'c';
    }            

    putchar(ch);

    Sleep(200);
}

If you want the timer to also stop, you could do something like this:

while (time(NULL) - startTime < 2)
{
    if(_kbhit()) {
        int x = _getch();

        if(x == 't') {

            // Save the current time difference
            int currentDiff = time(NULL) - startTime;

            // Loop until 't' is pressed again
            while(1) {
                putchar('S');
                Sleep(200);
                if(_kbhit()) {
                    x = _getch();
                    if(x == 't') break;
                }
           }

           // And restore it so it continues where it stopped
           startTime = time(NULL) - currentDiff; 

           // If you want to restart the timer completely, do this instead
           // startTime = time(NULL);
       }
    }            

    putchar('o');

    Sleep(200);
}

Note that this is not perfect. But it's enough to get you going.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM