How to use getch() without waiting for input?

Fairlight picture Fairlight · Jul 20, 2014 · Viewed 7.1k times · Source
 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");
}

Let's say that's my incremental game. I want refresh my game after 1 second. How can I make getch() to wait for input without stopping all other stuff?

Answer

Mario picture Mario · Mar 20, 2015

Use khbit() function to detect if a key was pressed :)

something like:

 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");
}