Why is adding a leading space in a scanf format string recommended?

前端 未结 2 372
别那么骄傲
别那么骄傲 2020-12-06 07:38

I am currently reading this book \"C11 Programming for beginners\" and in the scanf() chapter it says:

\"Always add a leading space before the first control string c

相关标签:
2条回答
  • 2020-12-06 08:10

    @WhozCraig well stated shortcomings to this advice. Its comes without rational nor detail. Further it does not apply to "%s" as "%s" consumes leading white-space with or without a leading space.

    A leading white-space, be it ' ', '\t', '\n', etc. all do the same thing: direct scanf() to consume and not store optional leading white-space char. This is useful as typical usage of previous scanf() does not consume the user's '\n' from the Enter

    scanf("%d", &some_int);
    scanf("%c", &some_char);  // some_char is bound to get the value '\n'
    

    All scanf() input specifiers ignore leading spaces, except 3: "%c", "%n", "%[]".

    Simply directive do benefit with the leading space as in the following. Previous left-over white-space is consumed before '$'.

    int Money;
    scanf(" $%d", &Money);
    

    Often, though not always a leading space before "%c" is beneficial as when reading a single char of user input.

    char ch;
    scanf(" %c", &ch);
    

    What is most wrong with the advice is that 1) when using "%s", supplying a width parameter is essential to robust code and 2) the return value should be checked.

    char buf[30];
    int cnt = scanf("%29s", buf);
    if (cnt != 1) Handle_NoInput_or_EOF_IOError();
    

    Lastly, recommend to use fgets() over scanf() as one can - which is the usually the case.

    0 讨论(0)
  • 2020-12-06 08:17

    "Always add a leading space before the first control string character to ensure accurate character input."

    This is to consume any trailing character in the stdin that might have been left by previous user input (like the carriage return), before the scanf reads the user input.

    0 讨论(0)
提交回复
热议问题