Reputation: 35
I have this code that makes a working timer that fits perfectly for my game! It does everything right, their is just once small issue. When ever the clockTicker less than 10, the clock displays the time like 0:4, instead I want it to display like 0:04. I tried this code out, cout << setfill('0') << setw(2) << clockTicker. Which works perfectly! The 0 will only in front of the number when it's less than 10! But I need to save the clockTicker in a text document for my game also, which technically. The 0 doesn't "save" itself in front of the int. So my question is, if the clockTicker is less than zero, how can I add a 0 in front of the number, AND save it into the variable like so. Example: 0:08. 1:04
#include <iostream>
#include <Windows.h>
using namespace std;
void clickTime(int &, int, const int); // Timer for the display clock
//---- Display Clock----------------------------------------
const int Time = 0;
int Minute = 0;
int loopRepeats = 0;
int clockTicker = Time;
bool stoptimer = false;
// Set position of text
void CPos(int x, int y)
{
COORD cPos;
cPos.X = x;
cPos.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cPos);
}
int main()
{
while(stoptimer == false)
{
clickTime(clockTicker,loopRepeats,Time);
loopRepeats++;
CPos(0, 0); cout << " Time is: ";
cout << Minute << ":" << clockTicker;
Sleep(100); // This is the game of the game's speed
}
return 0;
}
void clickTime(int &time, int loops, const int Time)
{
if(stoptimer == false)
{
// This tells the program after the loop repeats 7 times, to decrement a second!
if((loops % 8) == 7){
time++;
}
// This says if timer is 60 seconds, add a minute, reset time!
if(time == 60){
++Minute;
clockTicker = 0;
}
} // end if
}
Upvotes: 0
Views: 1419
Reputation: 385194
You don't.
Numbers are numbers are numbers are numbers. Not decimal, human-readable representations. They are numbers. They don't have zero-padding. Zero-padding only affects serialisation.
You have correctly discovered how to zero-pad a number when you serialise it into std::cout
; now simply do the same when you serialise it into a std::ofstream
. They are both output streams, with the same interface: that you're streaming into a text file rather than to console does not matter.
Upvotes: 5
Reputation: 699
Wouldn't a simple if statement do the job?
int main()
{
string separator; // separator variable
while(stoptimer == false)
{
clickTime(clockTicker,loopRepeats,Time);
loopRepeats++;
CPos(0, 0); cout << " Time is: ";
if(clockTicker < 10) // check if it is neccesary to adapt the separator
separator = ":0"; // include a 0 in the separator
else
separator = ":"; // else don't
cout << Minute << separator << clockTicker; // use a variable instead of a set value
Sleep(100); // This is the game of the game's speed
}
return 0;
}
Upvotes: -2