繁体   English   中英

C ++游戏时钟计时器

[英]C++ Game Clock Timer

我有这段代码可以使计时器正常运行,非常适合我的游戏! 它做对了所有事情,这只是一个小问题。 每当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
}

你不知道

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

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

一个简单的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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM