c++ - 10 秒后运行代码或按下某个键

标签 c++

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

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

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

    cout<<"a";

}//while1

你能给我一些更好的建议吗?

谢谢

最佳答案

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

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

关于c++ - 10 秒后运行代码或按下某个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13861509/

相关文章:

c++ - 如何正确初始化宽字符串?

c++ - 用于常见操作的标准一元函数

c++ - 如何从 C++ multimap 中删除特定对?

c++ - 专门针对 bool + integral + floating-point 返回类型的模板

c++ - 如何确定 SSD 驱动器是固定驱动器还是连接到 USB?

c++ - 如何从重载函数中调用父类成员函数?

C++ 从 back_insert_iterator 转换为仿函数中的迭代器

C++ 11 动态数组部分列表初始化(错误或误解)?

c++ - 如何针对 "suspicious sizeof"或 SIZEOF_MISMATCH 结果训练 Coverity?

c++ - 使用数组生成随机数