Write about formatted input and output functions in C

Estudies4you

4.1. I/O Using C Functions

Q11. Write about formatted input and output functions in C.
Answer:
Formatted Input-output Functions
Input and output operations are performed using predefined library functions.
There are two formatted input/output functions.
(a) scanf(): Used for formatted input and
(b) printf(): Used to obtain formatted output
(a) scanf()
This function is used to read values for variables from keyboard.
Syntax
scanf(“control string”, address_list);
(i) Control String
Control string is enclosed within double quotes.
It specifies the type of values that have to be read from keyboard.
Control string consists of field specification written in the form.% field specification.
Field formats for different data types are given below,
Format 
Type of Value
%d
%f
%c
%ld
%u
%lf
%s
%ox
%o
%i
%e
%g
Integer
Floating Numbers
Character
Long Integer
Unsigned Integer
Double
String type
Hexadecimal
Octal
 Decimal or Hexadecimal or Octal
Floating point number in exponential form
Floating point number with trailing zeros truncated

(ii) Address_list
It contains addresses of input/output variables preceded. The addresses are specified by preceding a variable by ‘&’ operator.
Examples
1. scanf(“%d %f c”, &i, &a, &b);
When user enters 10, 5.5, ‘z’ from keyboard, 10 is assigned to i, 5.5 is assigned to a and ‘z’ is assigned to b.
2. scanf (“%3d %2d”, &a, &b);
If input is 500 and 10, then 500 is assigned to a and 10 is assigned to b
3. It is not always advisable to use field width specifiers in scanf statements. It may sometimes assign wrong values to variables as shown in example below.
scanf(“%2d-%3d”, &a, &b);
Here, if 5004 and 10 is input, then 50.is assigned to a and 04 to 6 which is wrong assignment. Hence, generally field widths are not used with scanf statement.

(b)  printf()
printf() function is used to print result on-monitor.
Syntax
printf(“control string”, arg1, arg2,...., argn);
(i) Control string can have,
Format specifier given in the form % specifier
Escape sequence characters such as \t (tab), \n (new line), \b (blank) etc.
It can have a string that must be printed on console i.e., monitor.
(ii) arg1, arg2......, argn are variables whose values must be printed on the monitor in the format specified in control string.

Examples
1. printf(“%d %c”, num, ch);
2. printf(‘“hello world”);
3. printf(“%d \n %c”, num, ch);
In example 3, suppose num has value 5 and ch has value ‘a’ then output will be printed as,
5
a
The output is printed in two different lines because new line character has been used between %d and %c.
To Top