程序控制流程未按预期工作

2024-01-27

这是一个问题C。程序控制流程不符合预期。它要求输入字符 in 但未能要求输入字符 x。

int foo();

int main(int argc, const char * argv[]) {

    foo();
    return 0;
}



int foo(){

    char in;
    char x;
    printf("Do you wanna party \n");


    if((in = getchar()) == 'y')
        printf("Go Sleep!, I was kidding\n");
    else
        printf("Oh! you are so boaring..\n");


    printf("\nOk, Another Question\n");
    printf("Wanna Go to Sleep\n");


    if((x = getchar()) == 'y')
        printf("ok lets go, Sleepy Head\n");
    else
        printf("No, lets go\n");


    return 0;
}

To clarify the comments mentioned above, in the process of giving input, you're pressing Y and then pressing ENTER. So, the y is considered as the input to first getchar(), and the ENTER key press [\n] is stored in the input buffer.

在通话中getchar(), the \n被读取,这被认为是完全有效的输入getchar()因此您的代码不会等待下一个输入。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

程序控制流程未按预期工作 的相关文章

随机推荐