samedi 31 mars 2018

Mystical anomaly with getch();

Today i was testing how key pressing might work in C++ and made simple loop for it,and found that getch() duplicate itself for some reason or idk what is going on honestly,just look at that:

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

#define VK_H 0x48
using namespace std;

int main()
{
int n=1;
int total=0;
bool theEnd=true;

while(theEnd)
{
    cout<<total<<endl;
    getch();

    if(GetAsyncKeyState(VK_LEFT))
    {
        total -=n;
    }else if(GetAsyncKeyState(VK_RIGHT))
    {
        total +=n;
    }else if(GetAsyncKeyState(VK_LSHIFT) && GetAsyncKeyState(VK_F1))
    {
        total = 0;
    } else if(GetAsyncKeyState(VK_ESCAPE))
    {
        break;
    }
}
cout<<total<<endl;
}

Its pretty simple.Program starts with a loop,where endlessly outputs value of variable "total",and after pressing left/right buttons "total" decrements/increments by 1.

Its was worked fine and perfect when i was using system("pause"); Sleep(milliseconds); cin.get();(but this one assume pressing enter each time,so it is not proper one) ,all that output right value on the screen after each pressing on the buttons.But in case with getch(); it somehow appear to working like only one time per/two cycles of the loop.

So the result i've get is like this: i'm pressing button right - current loop working fine,but next one working like without getch()...

I've siting and thinking couple hours,trying find any answers in google and here but nothing...

P.S.without using getch() or other things for purpose stoping loop till next pressing - it will add not +1 to total by single pressing(as i need),but hundreds(average pressing key will do 150-300 loops lol).

Aucun commentaire:

Enregistrer un commentaire