如何使用getch()而不等待输入?

时间:2014-07-20 08:34:19

标签: c++ windows input getch conio

 for (;;)
{
    cout << "You are playing for:" << playtime << "seconds." << endl;
    cout << "You have " << bytes << " bytes." << endl;
    cout << "You are compiling " << bps << " bytes per second." << endl;
    cout << "Press a to buy assembler monkey (produces 1 byte per second)/(cost 10 bytes)" << endl;
    switch(getch())
    {
        case 'a': bytes = bytes - 10; bps++; break;
    }
    bytes = bytes + bps;
playtime++;
Sleep(1000);
system("cls");
}

让我们说这是我的增量游戏。我想在1秒后刷新我的游戏。如何让getch()等待输入而不停止所有其他东西?

3 个答案:

答案 0 :(得分:3)

使用 khbit()函数检测是否按下了某个键:)

类似的东西:

 for (;;)
{
    cout << "You are playing for:" << playtime << "seconds." << endl;
    cout << "You have " << bytes << " bytes." << endl;
    cout << "You are compiling " << bps << " bytes per second." << endl;
    cout << "Press a to buy assembler monkey (produces 1 byte per second)/(cost 10 bytes)" << endl;
    if(kbhit()){  //is true when a key was pressed
        char c = getch();   //capture the key code and insert into c

        switch(c)
        {
            case 'a': bytes = bytes - 10; bps++; break;
        }
    }
    bytes = bytes + bps;
    playtime++;
    Sleep(1000);
    system("cls");
}

答案 1 :(得分:1)

您可以使用其他线程来获取用户输入。

for (;;)是不必要的,您应该使用while (true)

#include <Windows.h>
#include <iostream>
#include <conio.h>

using namespace std;

DWORD WINAPI SpeedThread(LPVOID lpParam);



int main ()
{
    int playtime = 0,
        bytes = 0,
        bps = 1;

    bool bKeyPressed = false;

    CreateThread( NULL, 0, SpeedThread, &bKeyPressed, 0, NULL);

    while (true)
    {
        cout << "You are playing for:" << playtime << "seconds." << endl;
        cout << "You have " << bytes << " bytes." << endl;
        cout << "You are compiling " << bps << " bytes per second." << endl;
        cout << "Press a to buy assembler monkey (produces 1 byte per second)/(cost 10 bytes)" << endl;
        if (bKeyPressed && bytes >= 10)
        {
            bytes -= 10;    
            bps++; 

            bKeyPressed = false;
        }
        bytes = bytes + bps;
        playtime++;
        Sleep(1000);
        system("cls");
    }

}

DWORD WINAPI SpeedThread (LPVOID lpParam)
{
    bool * bKeyPressed = (bool *) lpParam;

    while (true)
    {
        if (_getch () == 'a')
            *bKeyPressed = true;
    }
}

答案 2 :(得分:0)

对我有用的不是使用getch(),而是使用scanf()。 为了阻止scanf停止运行,您必须使用:

scanf("%c \n",example);

请记住,example是指针(char* example;