Reputation: 113
I was wondering what happens in an instance such as:
printf("How many sides do the polygon has: ");
scanf_s("%d",&n);
That is, when scanf expects the input to be an integer, but instead the user enters a float value, a double, or anything else.......Is the value then assigned to the variable, or is it just present at the background? Can it's presence somehow act detrimentally on how the programme works later on?
Upvotes: 0
Views: 1080
Reputation: 72256
but instead the user enters a float value, a double, or anything else
The user always enters a string of characters. This is how I/O works.
Using the format string, scanf()
attempts to extract from the input string the first substring that looks like the text representation of data that uses the format specifier then it recovers the data that would produce the aforementioned text representation when formatted using printf()
with the same format specifier.
In your example, because of %d
, scanf()
uses from the input string as many digits it finds at the beginning of the string. It skips the leading spaces, reads an optional sign if it is present, reads the digits and stops reading when it reaches a non-digit character. It uses the sign and the read digits to re-create the number and puts it at the address it receives as argument.
It uses the rest of the string to fulfill the next format specifier, if any or ignores it completely (but it doesn't consume it) if there are no more specifiers in the format string.
Upvotes: 4
Reputation: 9062
This is specified in the scanf
documentation:
Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character
Under the d
specifier, the characters extracted are:
Any number of decimal digits (0-9), optionally preceded by a sign (+ or -). d is for a signed argument, and u for an unsigned.
Thus, it consumes from the stream all the leading whitespace characters and the first number (the +/- sign and an integer) and stops if there is a character that does not match.
Furthermore,
at least one character shall be consumed by any specifier. Otherwise the match fails, and the scan ends there.
Upvotes: 3