The above mapping of data types and corresponding format specifiers is also applicable to
scanf
function. The %c
format specifier is used to read a single character from the standard input, %s
specifier allows to read a string with a whitespace character as terminating character (space, line feed, carriage return etc.) and similar with other datatypes.
There is a difference in the use of
gets
and scanf
with %s
specifier. If you use scanf,
it will read a string from input until a whitespace character is read. But gets
will read a string until a newline character (\n
) is reached. So if you use scanf("%s", line)
, where the line is a character array, and your input is a string "Nice C tutorial"
, after execution of this this statement you will get string "Nice"
in the variable line
. Because "Nice"
is followed by a whitespace character (blank space). But using gets
will populate the variable line
with the whole string.
We can also specify maximum field width in the
scanf
. It is done by adding a number after % and before the specifier to limit the width of the input. Let's take a look at it with the help of an example,
- #include <stdio.h>
- int main(void) {
- int a;
- printf("Enter number: ");
- scanf("%5d", &a);
- printf("Formatted number is: %d", a);
- return 0;
- }
- Output:
- Enter number: 123456
- Formatted number is: 12345
In the above program, the format specifier used with
scanf
statement is %5d
. This means, only the first 5 characters will be read into the variable. So the input '123456' is trimmed down to '12345'.
This can be applied to
printf
as well. But the result is quite different. If a variable has the value '123' and you use %5d
in a printf
statement, you will get 5 characters as output with leading two blank space and then three digit, but if you use %2d
it will print all 3 digits.
No comments:
Post a Comment