Need a project done?

C++ Programming Developer

Search This Blog

How to make Timer in C++ without clearing whole screen i.e. without system("cls")

#include<iostream>
#include<windows.h>//for using Sleep => Pauses execution of program, where ever used.
using namespace std;

int main()
{
for (int minutes = 2; minutes>=0; minutes--)
{
for (int seconds = 59; seconds>=0; seconds--)
{
cout<<minutes<<":"<<seconds;
Sleep (1000); //System pauses for 1000 milliseconds i.e. 1 second.
cout<<"\r";//Removes the timer i.e. the line on which timer is running. You can replace this line by //system("cls");
}
}
 return 0;
}

You might not be sure about the last step. \r is carriage return. When used alone as I have used, it removes the current line. And normally it's used to bring the cursor to the starting of line. As I've used in my Decimal to Binary Converter.
This is an efficient way, you can use system("cls") command, which clears whole screen and then prints the timer again (and loop is continued like this) whereas \r is clearing only one single line. \r is efficient because there may be a scenario in which we don't want our whole of the screen to be cleared and then we'll have to reprint our whole screen.
Feel free to ask if you still have queries.
"Don't let anyone ever make you feel like you don't deserve what you want."