帮我看看我的C++这段代码有什么问题

来源:百度知道 编辑:UC知道 时间:2024/05/18 06:27:19
是用来实现计时器的,调的时候,发现如果计数累加中,随便多按按无关紧要的键,再按空格暂停会停不下来有时还会清零了,但如果无关紧要的键按的较少就不会有这种问题,谢谢了
#include <iostream.h>
#include <windows.h>
#include <time.h>
#include <stdio.h>
#include <iomanip.h>
#include <conio.h>

void add();
int h,m,s;
char key;
bool key_click=false;
main()
{
do
{
h=m=s=0;
system("cls");
cout<<" "<<setw(2)<<h<<" : "<<setw(2)<<m<<" : "<<setw(3)<<s<<endl;
do key=getch();while (key!=' ');//空格 开始
do
{
do
{
add();
key=getch();
}while(key!=' ');//空格 暂停
do key=getch();while(key!=' '&&key!='c');
if(key=='c')key_click=true;//C键 归零
}while(!key_click);
}while(1);
}

void add() /

楼主你的代码逻辑太混乱了,我猜测你是想做个定时器吧,别用Sleep()延时900多毫秒,会阻塞进程,按键得不到及时相应。我改进一下代码,如下所示:

#include <iostream.h>
#include <windows.h>
#include <time.h>
#include <stdio.h>
#include <iomanip.h>
#include <conio.h>

int h, m, s;

void refresh();
void add();

int main()
{
char key;
bool bStart = false;

h = m = s = 0;
refresh();

while(1)
{
if(kbhit())
{
key = getch();
if(key == ' ') bStart = !bStart;
else if(key == 'c')
{
h = m = s = 0; //C键归零
refresh();
}
}

if(bStart) add();
}

return 0;
}

void refresh()
{
system("cls"); //clear screen
cout<<" "<<setw(2)<<h<<" : "<<setw(2)<<m<<" : "<<setw(3)<&