我目前正在用C ++制作游戏。我下面有一个计时器功能:
void timer(int &s , int &m , bool a)
{
while (a)
{
Sleep(1000);
if (s%60)
m+=1;
s+=1;
}
}
这是游戏的功能:
void game()
{
int s = 0 , m = 0;
char a[]="Computers";
char b[10];
timer(s,m,true);
while (strcmpi(a,b)!=0)
{
cout<<"Guess the word:";
gets(b);
}
timer(s,m,false);
cout<<"You got it correct!\n";
cout<<"Time taken : "<<m<<':'<<s<<endl;
}
当我运行程序时,什么也没发生。我猜计时器正在运行,并且不允许在while循环中game()
执行。
因此,基本上我正在尝试找出用户正确猜出单词所需的时间。
我该如何克服这个问题?
提前致谢 :)
如果您只想花费时间,请取消计时器。询问用户开始的时间,将其存储,然后从用户结束的时间中减去开始时间。
void game()
{
int s = 0 , m = 0;
char a[]="Computers";
char b[10];
time_t start = time(NULL); <<<< Modification here
while (strcmpi(a,b)!=0)
{
cout<<"Guess the word:";
gets(b);
}
cout<<"You got it correct!\n";
time _t taken = time(NULL) - start;
m = taken / 60; <<<< Modification here
s = taken % 60; <<<< Modification here
cout<<"Time taken : "<< m <<':'<<s<<endl;
}
如果分配允许,请考虑将char
sa和b替换为string
sa和b。用户不能像使用char数组和时那样,溢出字符串并在程序上造成严重破坏gets
。
void game()
{
int s = 0 , m = 0;
std::string a ="Computers"; <<<< Modification here
std::string b; <<<< Modification here
time_t start = time(NULL);
do
{
cout<<"Guess the word:";
cin>> b; <<<< Modification here
} while (a != b); <<<< Modification here. No sense testing b before you read b
cout<<"You got it correct!\n";
time _t taken = time(NULL) - start;
m = taken / 60;
s = taken % 60;
cout<<"Time taken : "<< m <<':'<<s<<endl;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句