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.
You might be running into a little bug with
_getch(). On SDK10.0.17134.0the bug is that_getch()will return the key that was pressed and on the next call return 0.Without breakpoints, the
_kbhitmight return true more than once, which would put 0 intocand yourif(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_kbhitwould no longer return true. Once the loop exits, you will have had a non-zero value inc.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)