C scanf() and fgets() problem

时间秒杀一切 提交于 2019-11-28 09:32:50

This is the problem with using scanf() to take in user input, it's not made to handle strings or any bad inputs. scanf() is meant to read formatted input (e.g., files with a strict and specific format). When taking in input from the user, input could be malformed and causes problems. You should use fgets() to read the input and parse it yourself.

To answer why the second scanf() call gets skipped, it's because the first call only consumes the digits that gets inputted. However the newline from pressing Enter remains in the input buffer and is in turn, the input of the second call. To fix this, you'd want to remove that newline character from the input buffers. The safest way to do that would be to use getchar() until the newline character is read, then continue with your program. And avoid using the fflush(stdin) pattern, that's not safe and can cause more problems than it's worth.

Here's a simple function you can use to read characters until a newline is read:

void clear_newlines(void)
{
    int c;
    do
    {
        c = getchar();
    } while (c != '\n' && c != EOF);
}

Call this after any call to scanf() that you're processing non-string data.

    scanf("%d",&choice);
    fgetc(stdin);

what i did is to read the fgetc from stdin and this leave the '\n' so your buffer is crear.

the first line of the code:

scanf(%d, &input);

should be :

scanf("%d", &input);

i.e. the quotes are missing

scanf("%[^\t\n]", &na);

should be:

scanf("%[^\t\n]", na);

ie., remove the &

Also fgets should work fine except that it will include the newline from when the user presses enter. You will have to strip it off.

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