Search code examples
c++countdown

Q: remaining 0 printed after using "\r" in C++ code


I created a program that works like a countdown and I ran into an error: Everything is printed fine until the seconds fall (counter.second) bellow 10, then it prints 90 instead of 9 ( or 09 ), 80 instead of 8 and so on.

If I remove "\r" the "Time remaining text" will be printed the "counter" amount of times besides one another, without this error, but that would fill my cmd which is worse.

Other than that, everything works as expected.

Any ideas on how to fix this?

#include <iostream>
#include <windows.h>

int main() {
    std::pair<int, int> counter;
    std::pair<int, int> aux;

    std::cin >> counter.first;
    std::cin >> counter.second;

    while (1) {

        aux.first = counter.first;
        aux.second = counter.second;

        while (aux.first >= 0 && aux.second >= 0)
        {
            std::cout << "\rTime remaining: " << aux.first << ":" << aux.second << std::flush;
         
            Sleep(1000);  

            if (aux.second == 0) {
                aux.first--;
                aux.second = 60;
            }
            aux.second--; 
        }
        PlaySound(TEXT("retro.wav"), NULL, SND_ASYNC);
    }

    return 0;
}

Solution

  • Well, take a look: If you write

    I like cats.
    

    And then cover it with

    I like dogs.
    

    Everything's fine. But if you cover it with

    I like.
    

    Then cats. remain uncovered.

    I like.cats.
    

    This is what happens. You try to cover 10 with 9. The 0 remains uncovered. You can fix it with a space after that for example.