功能参数和getch()的奇怪行为 [英] Strange behavior with function parameters and getch()

查看:142
本文介绍了功能参数和getch()的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



以下面的代码为例:

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

printf(%c\\\
,c);

返回0;

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

使用此代码按下某个键时,无论如何,打印'a',这是第一个功能的参数。问题是,'a'不是被调用的第二个函数的参数,而'a'仍然被打印而不是'b'。为什么发生这种情况?

解决方案

想想看:您的程序在做什么?你击中了键盘上的一个字符。当主要完成睡眠时,它用'a'调用函数。由于kbhit是真的,它会打印'a'。然后,立即再次调用IsKeyDown()。由于kbhit现在是false,它将返回而不打印任何内容。然后再次睡眠,并重新开始。



为了测试这个,如果IsKeyDown得到一个字符,则返回1。然后在main中,测试返回值以查看发生了什么。


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?

解决方案

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.

这篇关于功能参数和getch()的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆