我有这个代码,使一个工作计时器适合我的游戏!它做的一切都正确,它们只是一个小问题.当clockTicker小于10时,时钟显示时间为0:4,而我希望它显示为0:04.我试过这个代码,cout << setfill('0')<< setw(2)<< clockTicker.哪个效果很好!当数小于10时,0只会在数字前面!但我需要将clockTicker保存在我的游戏的文本文档中,这在技术上也是如此.0不会在int前面"保存"自己.所以我的问题是,如果clockTicker小于零,我怎么能在数字前添加一个0,并将其保存到变量中,如此.示例: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
}
Run Code Online (Sandbox Code Playgroud)
你没有.
数字是数字,数字是数字.不是十进制的,人类可读的表示.他们是数字.它们没有零填充.零填充仅影响序列化.
您已经正确地发现了在将数字序列化时如何对数字进行零填充std::cout; 现在,当你将它序列化为一个时,就会这样做std::ofstream.它们都是输出流,具有相同的接口:您将流式传输到文本文件而不是控制台无关紧要.