scanf/getchar working correctly only first time through loop? [duplicate]

混江龙づ霸主 提交于 2019-12-04 20:11:45

You need to digest the newline after the scanf. You can do what you're doing above in the code:

scanf(" %d", &n);
while(getchar() != '\n');
first = add_to_list(first, n);

Can I recommend that you use fgets as a safer alternative to getchar and scanf?

As you've noticed these functions can buffer the newline and pass it on to the next function that reads from the standard input.

With fgets you can store the input in a char array and avoid such problems. Additionally, you can still check easily if the input consists of only a newline:

char user_input[10] = "";

printf("Would you like enter an integer ((y) for yes/(n) for no):\n");

/* get input or quit if only newline is entered, we only check the first char */
while(fgets(user_input, 3, stdin)[0] != '\n') 
{
    /* check if the first char is 'y', quicker to do than using strcmp */
    if(user_input[0] == 'y') 
    {
        int input = 0;

        printf("Enter an Integer: ");

        fgets(user_input, 5, stdin); /* get input again */

        input = atoi(user_input);    /* convert to int */

        printf("Your integer is %d\n", input);

        printf("Would you like to go again? y/n:\n");
    }
    else
    {
        return printf("No input there.\n");
    }
}

getcharis get the data from stdin, while(getchar() != '\n'); just like clear the stdin buffer. so the following code can work correctly

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