前几天做题的时候遇到了scanf函数读取失败的情况,今天详细了解了下scanf函数。
资料来源:
std::scanf, std::fscanf, std::sscanf - cppreference.com
C string that contains a sequence of characters that control how characters extracted from the stream are treated:
- Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- seeisspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).
- Non-whitespace character, except format specifier (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread.
- Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the stream and stored into the locations pointed by the additional arguments.
All conversion specifiers other than [
, c
, and n
consume and discard all leading whitespace characters (determined as if by calling isspace) before attempting to parse the input. These consumed characters do not count towards the specified maximum field width.
--------------------------------------------------------------------------
Because most conversion specifiers first consume all consecutive whitespace, code such as
std::scanf("%d", &a); std::scanf("%d", &b);
will read two integers that are entered on different lines (second %d will consume the newline left over by the first) or on the same line, separated by spaces or tabs (second %d will consume the spaces or tabs).
The conversion specifiers that do not consume leading whitespace, such as %c, can be made to do so by using a whitespace character in the format string:std::scanf("%d", &a); std::scanf(" %c", &c); // ignore the endline after %d, then read a char