C ++游戏时钟计时器

时间:2015-04-10 10:33:42

标签: c++ clock

我有这个代码,使一个适合我的游戏的工作计时器!它做的一切都正确,它们只是一个小问题。当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
}

2 个答案:

答案 0 :(得分:5)

你没有。

数字是数字,数字是数字。不是十进制的,人类可读的表示。它们是数字。他们没有零填充。零填充仅影响序列化

您已正确发现在将数字序列化为std::cout时如何对数字进行零填充;现在,当您将其序列化为std::ofstream时,只需执行相同操作即可。它们都是输出流,具有相同的界面:您将流式传输到文本文件而不是控制台并不重要。

答案 1 :(得分:-2)

这个工作不是一个简单的if语句吗?

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;
}
相关问题