c++cvisual-studiokbhit

Why would this exemple only works with a breakpoint


I'm creating a basic console application in C/C++.

In the following example I'm repeatedly writing some char to the console with a 50ms delay and I want it to exit the program when I hit a key.

#include "pch.h"
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <conio.h>

int PauseRet(int iDuree) {
    unsigned int uiTemps = GetTickCount();
    int iVal = 0;
    do {
        if (_kbhit()) {
            iVal = _getch();
        }

    } while ((GetTickCount() - uiTemps) < (unsigned int)iDuree);

    return iVal;
}

int main()
{
    char c = 0;
    int iTempo = 50;
    while (true) {


        putchar('a');

        c = PauseRet(iTempo);


        if (c) {

            return 0;
        }

    }
}

My problem is that in my project it goes into the condition if(c){... only when I put a break point here:

    if (_kbhit()) {
        <BREAKPOINT> iVal = _getch();
    }

I'm using visual studio 2017.

I've tried this code on another PC in a new project and I didn't had any problem

I believe this has something to do with my project settings.


Solution

  • You might be running into a little bug with _getch(). On SDK 10.0.17134.0the bug is that _getch() will return the key that was pressed and on the next call return 0.

    Without breakpoints, the _kbhit might return true more than once, which would put 0 into c and your if(c) would never pass.
    With breakpoints, once you've pressed the key, it would stop there, the key would subsequently be released in time and once you continue from the breakpoint, _getch() would return the key that was pressed, and _kbhit would no longer return true. Once the loop exits, you will have had a non-zero value in c.

    To fix this, update your SDK by running the VS 2017 setup again and updating (or downgrading to something before april update) and/or downloading newer SDK or use _getwch()

    Relevant MS Dev Community bug report. (fixed)