The program control flow doesn't work as expected

时光怂恿深爱的人放手 提交于 2019-12-09 03:58:54

问题


This is a problem in C. The program Control flow is not as expected. It ask to enter the character in but fail to ask to enter character 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;
}

回答1:


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.

On the call to next getchar(), the \n is read, which is considered a perfectly valid input for getchar() and hence your code is not waiting for the next input.



来源:https://stackoverflow.com/questions/27513046/the-program-control-flow-doesnt-work-as-expected

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