0
bool stop = false;
    int hours = 0;
    int minutes = 0;
    int seconds = 0;
    while (stop == false)
    {
        system("cls");
        cout << "Hours     Minutes     Seconds\n";
        cout << hours << "          " << minutes << "          " << seconds << endl;
        Sleep(1000);
        seconds++;
        if (seconds == 60)
        {
            minutes++;
            if (minutes == 60)
            {
                hours++;
                minutes = 0;
            }
            seconds = 0;
        }
    }

I want to exit the while loop somehow but the only way I can think of would be to ask for user input, but I can't do this because it would mess up the stopwatch.

drescherjm
  • 10,365
  • 5
  • 44
  • 64
  • What is the purpose of the program? – kometen Dec 09 '20 at 20:54
  • 1
    Either set your loop condition to false or consider https://en.cppreference.com/w/cpp/language/break – TheUndeadFish Dec 09 '20 at 20:55
  • ***somehow but the only way I can think of would be to ask for user input*** You may want some OS api for that if you want to have it exit the loop when the user presses the space bar or something. Related: [https://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed](https://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed) – drescherjm Dec 09 '20 at 21:14
  • Since your on Windows, you can use [`_kbhit`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/kbhit?view=msvc-160). – Paul Sanders Dec 09 '20 at 21:18
  • This program is a stopwatch, I need to end the loop upon user input, I tried kbhit and getch but they didn't work can you show me how that would be done? – Kareem Fareed Dec 09 '20 at 22:25
  • Change `while (stop == false) {` to `while(!_kbhit()) {` – drescherjm Dec 09 '20 at 22:38
  • Thank you so much! – Kareem Fareed Dec 09 '20 at 23:16

1 Answers1

0
bool stop = false;
int hours = 0;
int minutes = 0;
int seconds = 0;
while (!_kbhit())
{
    system("cls");
    cout << "Hours     Minutes     Seconds\n";
    cout << hours << "          " << minutes << "          " << seconds << endl;
    Sleep(1000);
    seconds++;
    if (seconds == 60)
    {
        minutes++;
        if (minutes == 60)
        {
            hours++;
            minutes = 0;
        }
        seconds = 0;
    }
}