1

I want to write a timer program which shows the time from x seconds to 0 seconds, for example, if x=10s: 10s - 9s - 8s ... 1s. Yet, I want to erase the previous time each second: when the program writes "9s" in cout I want to erase "10s". Do you know how to erase the previous line wrote in std::cout ? I'm on linux but I'd want the code to be portable if that may be possible.

I tried std::cout << "\r"; but it didn't work, for example, whit a ten seconds timer, the program waits ten seconds and then writes "1s".

Here my code:

#include <iostream>
#include <thread>
#include <chrono>

std::string convert(unsigned short int seconds);

int main()
{
    unsigned short int seconds {};
    std::cout << "Entrez le temps en secondes du minuteur : ";
    std::cin >> seconds;
    std::cout << std::endl;
    for (unsigned short int i {seconds}; i != 0; i--)
    {
        std::string time {convert(i)};
        std::cout << '\r' << time ;
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
    return 0;
}

std::string convert(unsigned short int seconds)
{
    if (seconds < 60)
        return std::to_string(seconds) + "s";
    else if (seconds >= 60 && seconds < 3600)
        return std::to_string(seconds/60) + "min " + std::to_string(seconds%60) + "s";
    else
        return std::to_string(seconds/3600) + "h " + std::to_string((seconds%3600)/60) + "min " + std::to_string(seconds%60) + "s";       
}

Thank you for your help.

1 Answers1

3

you don't flush your buffer, so you see only the last line, cout could be flushed manually using std::cout.flush(); also you should keep in mind that your code rewrites only the begining of the line, so 10s will be changed to 9ss.

this will help

 std::cout << '\r' << time;
 std::cout.flush();
bobra
  • 615
  • 3
  • 18