1

我是 C++ 的初学者,我需要创建一个应用程序来在 10 秒后或按下一个键后打印一些东西,我尝试了这段代码但它不起作用(按下一个键后它会打印“a”很多而不是一个“a”)

int i;
while(1)
{
    i=1;

    while(!kbhit()||i<1000)
    {
        Sleep(10);
        i++;
    }

    cout<<"a";

}//while1

你能建议我更好的方法吗?

谢谢

4

2 回答 2

1

问题是您没有从缓冲区中取出第一个键...

int i;
while(1)
{
    i = 0;
    while(!kbhit() && ++i<1000)
    {
        Sleep(10);
    }

    if (kbhit()) getch(); // to get the key out of the buffer, otherwise kbhit will keep getting true.
    cout<<"a";

}//while1
于 2012-12-13T14:11:28.020 回答
0

首先,您的代码最大的问题是无论您是否按下某个键,它都会休眠 10 秒。这是我的建议。

#include <ctime>
#include <conio>
#include <iostream>
using namespace std;

inline int getTime()
{
    return static_cast<int>(static_cast<double>(clock())/CLOCKS_PER_SEC);
}

int main()
{
    int i = 1;
    int time, totaltime;

    cout << "hit q to quit\n";
    while(1)
    {
        i=1;
        totaltime = getTime();
        time = getTime() - totaltime;
        while(!_kbhit()&&time<5)
        {
            i++;
            time = getTime() - totaltime;
        }

        if (kbhit()) { 
            if(_getch() == 'q') return 0; cout << "you hit a key - hit q to quit\n"; 
        }
        else cout<<"you waited - hit q to quit\n";
    }

    return 0;
 }

现在该代码所做的实际上是为您的代码计时...一旦达到 5 秒,它将显示您已等待。如果你按下 q 以外的键,它会告诉你。q 显然退出了。

于 2012-12-13T14:55:22.300 回答