Strange behavior with function parameters and getch()

时光毁灭记忆、已成空白 提交于 2019-12-11 04:28:50

问题


I am running in to some strange behavior with calling functions with parameters that contain getch().

Take the following code for example:

_Bool IsKeyDown(char c)
{
    if(!kbhit())
        return 0;
    char ch1 = getch();

    printf("%c\n", c);

    return 0;
}

/*
 * 
 */
int main(int argc, char** argv) {
    while(1)
    {
        IsKeyDown('a');
        IsKeyDown('b');
        Sleep(100);
    }
    return (EXIT_SUCCESS);
}

When a key is pressed with this code, no matter what, it will always print 'a', which is the parameter of the first function. The issue is, 'a' is not the parameter of the second function being called, yet 'a' is still printed instead of 'b'. Why is this occuring?


回答1:


Think about it: what is your program doing? You hit a character on the keyboard. When main finishes sleeping, it calls the function with 'a'. Since kbhit is true, it will print 'a'. Then, immediately, it calls IsKeyDown() again. Since kbhit is now false, it returns without printing anything. Then main sleeps again, and it starts over.

To test this, change IsKeyDown to return 1 if it gets a character. Then in main, test the return value to see what is happening.



来源:https://stackoverflow.com/questions/21177800/strange-behavior-with-function-parameters-and-getch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!