-1

I'm trying to exit a loop at anytime I want by pressing any key. I've tried the code below but it can't be done. Gotta need your help. Thank you in advance. I'm using a C-Free 5.0.

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

int main(void)
{
    int b=0, i;
    int seconds;
    printf("\nEnter number of seconds : ");
    scanf("%d", &seconds);
    while (b==0)
    {
        for(i=1;i<=seconds;i++)
        {
            time_t end = time(0) + 1;
            while(time(0) < end)
            ;
            seconds -= 1;
            printf("Number of seconds left : %d\n", seconds);
            b=kbhit();
        }

        if(seconds == 0)
        {
            exit(0);
        }
    }
    printf("Number of remaining seconds left : %d\n", seconds);
}
Jitzu Zu
  • 71
  • 1
  • 1
  • 4
  • 1
    What exactly is "C-Free 5.0"? If that's some obscure C compiler you probally better switch to gcc (mingw if you are on Window). – ThiefMaster Nov 24 '12 at 12:02
  • possible duplicate of http://stackoverflow.com/q/6731317/1273830 oh wait you already saw that question? kbhit? O_O – Prasanth Nov 24 '12 at 12:02

2 Answers2

1

You are "busy-waiting" in the innermost while loop. That might not be the best solution, but if that is what you want to do, you need to add a test in that loop to check if a key has been hit.

Thomas Padron-McCarthy
  • 27,232
  • 8
  • 51
  • 75
0

To exit a loop use a function in c++ called khbit. It becomes 1 when any key is pressed and to empty it again assign the key pressed to clear the buffer using getch()

#include <conio.h>
#include <iostream>

using namespace std;

int main()
{
    while(1)
    {
        if(kbhit())  // khbit will become 1 on key entry.
        {
            break;    // will break the loop
        }

                     // Try to use some delay like sleep(100);  // sleeps for 10th of second to avoid stress on CPU
    }

                     // If you want to use khbit again then you must clear it by char dump = getch();

                     // This way you can also take a decision that which key was pressed like 

                     // if(dump == 'A')

                     //{ cout<<"A was pressed e.t.c";}
}
Osaid
  • 557
  • 1
  • 8
  • 23