Why is the leading space added to the scanf format string?

I am currently reading this book, "C11 Programming for Beginners," and the scanf () chapter says:

"Always add a leading space before the character of the first control line to ensure accurate character input." How in:

scanf(" %s", whatever); 

The% s control string has a space before it. I know this sounds pretty self-evident, but I really don't understand what could go wrong, and how this space provides accurate character input.

Thanks in advance.

+5
source share
2 answers

@WhozCraig are the well-identified flaws of this tip. It comes without reasonable or detailed. It does not further refer to "%s" because "%s" consumes leading white space with or without leading space.

The leading white space, be it ' ' , '\t' , '\n' , etc., all do the same thing: direct scanf() to consume and not store the additional leading white space char . This is useful because the typical use of the previous scanf() does not consume the user '\n' from Enter

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

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

Just a directive brings an advantage with a leading space, as in the following. The previous remaining space is consumed before '$' .

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

Often, although not always leading space up to "%c" is useful, as when reading a single char user input.

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

The worst part about the tip is that 1) when using "%s" providing the width parameter is important for reliable code, and 2) you need to check the return value.

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

Finally, it is recommended that you use fgets() over scanf() , as you can, which is usually the case.

+3
source

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

This should consume any trailing character in stdin that could have been left by the previous user input (for example, carriage return ) before scanf reads the user input.

+1
source

Source: https://habr.com/ru/post/1204768/


All Articles