0% found this document useful (0 votes)
34 views

Chapter - 4

This document discusses input and output functions in C programming. It covers functions for reading single characters (getchar), writing characters (putchar), and formatted input and output of integer and real numbers using scanf. It explains that standard input/output functions require including the stdio.h header file. Functions covered allow basic input from the keyboard and output to the screen in C programs.

Uploaded by

Arif Istiaq
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Chapter - 4

This document discusses input and output functions in C programming. It covers functions for reading single characters (getchar), writing characters (putchar), and formatted input and output of integer and real numbers using scanf. It explains that standard input/output functions require including the stdio.h header file. Functions covered allow basic input from the keyboard and output to the screen in C programs.

Uploaded by

Arif Istiaq
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Introduction to C

Programming

Chapter 4

Managing Input and Output


Operations
Introduction
⚫ Reading, processing, and writing of data are the three
essential functions of a computer program. Most
programs take some data as input and display the
processed data, often known as information or results,
on a suitable medium.
⚫ So far we have seen two methods of providing data to
the program variables. One method is to assign values
to variables through the assignment statements such as
x =5; a = 0; and so on. Another method is to use the
input function scanf which can read data from a
keyboard.
⚫ For outputting results we have used extensively the
function printf which sends results out to a terminal. All
input/output operations are carried out through function
calls such as printf and scanf.
9/25/2022 Ref: Programming in ANSI C by 2
E.Balagurusamy
Introduction
⚫ There exist several functions that have more or less
become standard for input and output operations in C.
These functions are collectively known as the standard
I/O library.
⚫ each program that uses a standard input/output function
must contain the statement # include <stdio.h> at the
beginning.
⚫ The file name stdio.h is an abbrevation for standard
input-output header file. The instruction #include
<stdio.h> tells the compiler `to search for a file named
stdio.h and place its contents at this point in the
program'. The contents of the header file become part of
the source code when it is compiled.

9/25/2022 Ref: Programming in ANSI C by 3


E.Balagurusamy
Reading a Character
⚫ The simplest of all input/output operations is reading a
character from the 'standard input' unit (usually the
keyboard) and writing it to the 'standard output' unit
(usually the screen).
⚫ Reading a single character can be done by using the
function getchar. (This can also be done with the help of
the scanf function.The getchar takes the following form:
variable name getchar( );
⚫ variable_name is a valid C name that has been declared
as char type. When this statement is encountered, the
computer waits until a key is pressed and then assigns
this character as a value to getchar function.

9/25/2022 Ref: Programming in ANSI C by 4


E.Balagurusamy
Reading a Character
⚫ Since getchar is used on the right-hand side of an
assignment statement, the character value of getchar is
in turn assigned to the variable name on the left.
⚫ For example
char name;
name = getchar();
⚫ Will assign the character 'H' to the variable name when
we press the key H on the keyboard. Since getchar is a
function, it requires a set of parentheses as shown.

9/25/2022 Ref: Programming in ANSI C by 5


E.Balagurusamy
Reading a Character
⚫ Since getchar is used on the right-hand side of an
assignment statement, the character value of getchar is
in turn assigned to the variable name on the left.
⚫ For example
char name;
name = getchar();
⚫ Will assign the character 'H' to the variable name when
we press the key H on the keyboard. Since getchar is a
function, it requires a set of parentheses as shown.

9/25/2022 Ref: Programming in ANSI C by 6


E.Balagurusamy
Reading a Character
⚫ C supports many functions, which are given in Table 4.1.
These character functions are contained in the file
ctype.h and therefore the statement
⚫ #include<ctype.h> must be included in the program.

9/25/2022 Ref: Programming in ANSI C by 7


E.Balagurusamy
Writing a Character
⚫ Like getchar, there is an analogous function putchar for
writing characters one at a time to the terminal. It takes
the form as shown below:
putchar (variable_narne);
⚫ where variable_name is a type char variable containing a
character. This statement displays the character
contained in the variable_name at the terminal.
⚫ For example, the statements
answer = 'Y’;
putchar (answer);
will display the character Y on the screen. The statement
putchar (' \n’);
would cause the cursor on the screen to move to the
beginning of the next line.
9/25/2022 Ref: Programming in ANSI C by 8
E.Balagurusamy
Formatted Input
⚫ Formatted input refers to an input data that has been
arranged in a particular format. For example, consider
the following data:
15.75 123 John
⚫ This line contains three pieces of data, arranged in a
particular form. Such data has to be read conforming to
the format of its appearance.
⚫ For example, the first part of the data should be read into
a variable float, the second into int, and the third part into
char. This is possible in C using the scanf function.
(scanf means scan formatted.) The general form of scanf
is:
scanf("control string", argl, arg2,…. argn);

9/25/2022 Ref: Programming in ANSI C by 9


E.Balagurusamy
Cont.
⚫ The control string specifies the field format in which the
data is to be entered and the arguments argl, arg2,
argn specify the address of locations where the data is
stored.

⚫ Control string and arguments are separated by commas.


Control string (also known as format string) contains field
specifications, which direct the interpretation of input
data. It may include:
⚫ Field (or format) specifications, consisting of the
conversion character %, a data type character (or type
specifier), and an optional number, specifying the field
width.

9/25/2022 Ref: Programming in ANSI C by 10


E.Balagurusamy
Cont.
⚫ Blanks, tabs, or newlines.
⚫ Blanks, tabs and newlines are ignored. The data type
character indicates the type of data that is to be
assigned to the variable associated with the
corresponding argument. The field width specifier is
optional.

9/25/2022 Ref: Programming in ANSI C by 11


E.Balagurusamy
Inputting Integer Numbers
⚫ The field specification for reading an integer number is:
% w sd
⚫ The percentage sign (%) indicates that a conversion
specification follows. w is an integer number that
specifies the field width of the number to be read and d,
known as data type character, indicates that the number
to be read is in integer mode.
⚫ Consider the following example:
scanf (%2d %5d", &num1, &num2);
⚫ Data line:
50 31426
⚫ The value 50 is assigned to num1 and 31426 to num2.

9/25/2022 Ref: Programming in ANSI C by 12


E.Balagurusamy
Inputting Integer Numbers
⚫ Suppose the input data is as follows:
31426 50
⚫ The variable num1 will be assigned 31 (because of %2d)
and num2 will be assigned 426 (unread part of 31426).
⚫ The value 50 that is unread will be assigned to the first
variable in the next scant' call.
⚫ This kind of errors may be eliminated if we use the field
specifications without the field width specifications. That
is, the statement
scanf ("%d %d", &num1, &num2);
⚫ will read the data 31426 50 correctly and assign 31426
to num1 and 50 to num2.

9/25/2022 Ref: Programming in ANSI C by 13


E.Balagurusamy
Inputting Integer Numbers
⚫ Input data items must be separated by spaces, tabs
or newlines. Punctuation marks do not count as
separators. When the scanf function searches the
input data line for a value to be read, it will always
bypass any white space characters.
⚫ What happens if we enter a floating point number
instead of an integer? The fractional part may be
stripped away! Also, scanf may skip reading further
input.
⚫ When the scanf reads a particular value, reading of
the value will be terminated as soon as the number
of characters specified by the field width is reached
(if specified) or until a character that is not valid for
the value being read is encountered. In the case of
integers, valid characters are an optionally signed
sequence of digits.
9/25/2022 Ref: Programming in ANSI C by 14
E.Balagurusamy
Inputting Integer Numbers
⚫ An input field may be skipped by specifying * in the
place of field width. For example, the statement :
scanf(“%d %*d %d", &a, &b)
⚫ will assign the data 123 456 789
⚫ as follows
123 to a
456 skipped (because of *)
789 to b
⚫ The data type character d may be preceded by 'I'
(letter ell) to read long integers and h to read short
integers.

9/25/2022 Ref: Programming in ANSI C by 15


E.Balagurusamy
Inputting Real Numbers
⚫ Unlike integer numbers, the field width of real
numbers is not to be specified and therefore scant
reads real numbers using the simple specification %f
for both the notations, namely, decimal point notation
and exponential notation.
⚫ For example, the statement
scanf(“%f %f %f”, &x, &y, &z);
⚫ with the input data
⚫ 475.89 43.21E-1 678 will assign the value 475.89 to
x, 4.321 to y, and 678.0 to z. The input field
specifications may be separated by any arbitrary
blank spaces.
⚫ If the number to be read is of double type, then the
specification should be %If instead of simple %f. A
number may be skipped using %*f specification.
9/25/2022 Ref: Programming in ANSI C by 16
E.Balagurusamy
Inputting Character Strings
⚫ We have already seen how a single character can be
read from the terminal using the getchar function.
The same can be achieved using the scanf function
also.
⚫ In addition, a scanf function can input strings
containing more than one character.
⚫ Following are the specifications for reading character
strings:
%ws or %wc
⚫ The corresponding argument should be a pointer to a
character array. However, %c may be used to read a
single character when the argument is a pointer to a
char variable.

9/25/2022 Ref: Programming in ANSI C by 17


E.Balagurusamy
Inputting Character Strings
⚫ Some versions of scanf support the following
conversion specifications for strings:
% (characters]
% [^characters]
⚫ The specification %[characters] means that only the
characters specified within the brackets are
permissible in the input string. If the input string
contains any other character, the string will be
terminated at the first encounter of such a character.
⚫ The specification %[^characters] does exactly the
reverse. That is, the characters specified after the
circumflex (^) are not permitted in the input string.
The reading of the string will be terminated at the
encounter of one of these characters.

9/25/2022 Ref: Programming in ANSI C by 18


E.Balagurusamy
Reading Mixed Data Types
⚫ It is possible to use one scanf statement to input a
data line containing mixed mode data. In such cases,
care should be exercised to ensure that the input
data items match the control specifications in order
and type. When an attempt is made to read an item
that does not match the type expected, the scanf
function does not read any further and immediately
returns the values read.
⚫ The statement
scanf ("%d %c %f %s", &count, &code, &ratio, name);
⚫ will read the data 15 p 1.575 coffee
⚫ correctly and assign the values to the variables in the
order in which they appear. Some systems accept
integers in the place of real numbers and vice versa,
and the input data is converted to the type specified
in the control string. Ref: Programming in ANSI C by
9/25/2022 19
E.Balagurusamy
Reading Mixed Data Types
⚫ It is possible to use one scanf statement to input a
data line containing mixed mode data. In such cases,
care should be exercised to ensure that the input
data items match the control specifications in order
and type. When an attempt is made to read an item
that does not match the type expected, the scanf
function does not read any further and immediately
returns the values read.
⚫ The statement
scanf ("%d %c %f %s", &count, &code, &ratio, name);
⚫ will read the data 15 p 1.575 coffee
⚫ correctly and assign the values to the variables in the
order in which they appear. Some systems accept
integers in the place of real numbers and vice versa,
and the input data is converted to the type specified
in the control string. Ref: Programming in ANSI C by
9/25/2022 20
E.Balagurusamy
Reading Mixed Data Types
⚫ It is possible to use one scanf statement to input a
data line containing mixed mode data. In such cases,
care should be exercised to ensure that the input
data items match the control specifications in order
and type. When an attempt is made to read an item
that does not match the type expected, the scanf
function does not read any further and immediately
returns the values read.
⚫ The statement
scanf ("%d %c %f %s", &count, &code, &ratio, name);
⚫ will read the data 15 p 1.575 coffee
⚫ correctly and assign the values to the variables in the
order in which they appear. Some systems accept
integers in the place of real numbers and vice versa,
and the input data is converted to the type specified
in the control string. Ref: Programming in ANSI C by
9/25/2022 21
E.Balagurusamy
Reading Mixed Data Types

9/25/2022 Ref: Programming in ANSI C by 22


E.Balagurusamy
Rules for Scanf
⚫ Each variable to be read must have a filed
specification.
⚫ For each field specification, there must be a variable
address of proper type.
⚫ Any non-whitespace character used in the format
string must have a matching character in the user
input.
⚫ Never end the format string with whitespace. It is a
fatal error!
⚫ The scanf reads until:
⚫ A whitespace character is found in a numeric specification,
or
⚫ The maximum number of characters have been read or An
error is detected, or
⚫ The end of file is reached
9/25/2022 Ref: Programming in ANSI C by 23
E.Balagurusamy
Formatted Output
⚫ The printf statement provides certain features that
can be effectively exploited to control the alignment
and spacing of print-outs on the terminals.
⚫ The general form of printf statement is:
printf (“control string”, argl, arg2,…. argn);
Control string consists of three types of items:
⚫ Characters that will be printed on the screen as they
appear.
⚫ Format specifications that define the output format
for display of each item.
⚫ Escape sequence characters such as \n, \t, and b.

9/25/2022 Ref: Programming in ANSI C by 24


E.Balagurusamy
Formatted Output
⚫ The control string indicates how many arguments
follow and what their types are. The arguments argl,
arg2, argn are the variables whose values are
formatted and printed according to the specifications
of the control string. The arguments should match in
number, order and type with the format
specifications. A simple format specification has the
following form:
% w.p type-specifier
⚫ where w is an integer number that specifies the total
number of columns for the output value and p is
another integer number that specifies the number of
digits to the right of the decimal point (of a real
number) or the number of characters to be printed
from a string.
9/25/2022 Ref: Programming in ANSI C by 25
E.Balagurusamy
Formatted Output
⚫ Both w and p are optional. Some examples of
formatted printf statement are:

⚫ printf never supplies a newline automatically and therefore


multiple printf statements may be used to build one line of
output. A newline can be introduced by the help of a newline
character ' \ n' as shown in some of the examples above.

9/25/2022 Ref: Programming in ANSI C by 26


E.Balagurusamy
Output of integer numbers
⚫ The format specification for printing an integer
number is:
%w d
⚫ where w specifies the minimum field width for the
output. However, if a number is greater than the
specified field width, it will be printed in full,
overriding the minimum specification.
⚫ d specifies that the value to be printed is an integer.
The number is written right-justified in the given field
width. Leading blanks will appear as necessary.

⚫ The following examples illustrate the output of the


number 9876 under different formats:

9/25/2022 Ref: Programming in ANSI C by 27


E.Balagurusamy
Output of integer numbers

⚫ It is possible to force the printing to be left-justified by placing a


minus sign directly after the % character, as shown in the fourth
example above. It is also possible to pad with zeros the leading
blanks by placing a 0 (zero) before the field width specifier as
shown in the last item above. The minus (—) and zero (0) are
known as flags. Long integers may be printed by specifying Id
in the place of d in the format specification. Similarly, we may
use hd for printing short integers.
9/25/2022 Ref: Programming in ANSI C by 28
E.Balagurusamy
Output of Real numbers
⚫ The output of a real number may be displayed in
decimal notation using the following format
specification:
%w.p f
⚫ where w specifies the minimum field width for the
output. However, if a number is greater than the
specified field width, it will be printed in full,
overriding the minimum specification.
⚫ d specifies that the value to be printed is an integer.
The number is written right-justified in the given field
width. Leading blanks will appear as necessary.

⚫ The following examples illustrate the output of the


number 9876 under different formats:

9/25/2022 Ref: Programming in ANSI C by 29


E.Balagurusamy
Output of Real numbers
⚫ The integer w indicates the minimum number of
positions that are to be used for the display of the
value and the integer p indicates the number of digits
to be displayed after the decimal point (precision).
⚫ The value, when displayed, is rounded to p decimal
places and printed right-justified in the field of w
columns.
⚫ Leading blanks and trailing zeros will appear as
necessary. The default precision is 6 decimal places.
The negative numbers will be printed with the minus
sign. The number will be displayed in the form
[-] mmm-nnn
⚫ We can also display a real number in exponential
notation by using the specification:
% w.p e
9/25/2022 Ref: Programming in ANSI C by 30
E.Balagurusamy
Output of Real numbers
⚫ The display takes the form
⚫ [ - ] m.nnnn [±]xx
⚫ where the length of the string of n's is specified by the
precision p. The default precision is 6.
⚫ The field width w should satisfy the condition.
W ≥ p+7
⚫ The value will be rounded off and printed right justified in
the field of w columns. Padding the leading blanks with
zeros and printing with left-justification are also possible by
using flags 0 or - before the field width specifier w.
⚫ The following examples illustrate the output of the number
y = 98.7654 under different format specifications:

9/25/2022 Ref: Programming in ANSI C by 31


E.Balagurusamy
Output of Real numbers
⚫ The display takes the form
⚫ [ - ] m.nnnn [±]xx
⚫ where the length of the string of n's is specified by the
precision p. The default precision is 6.
⚫ The field width w should satisfy the condition.
W ≥ p+7
⚫ The value will be rounded off and printed right justified in
the field of w columns. Padding the leading blanks with
zeros and printing with left-justification are also possible by
using flags 0 or - before the field width specifier w.
⚫ The following examples illustrate the output of the number
y = 98.7654 under different format specifications:

9/25/2022 Ref: Programming in ANSI C by 32


E.Balagurusamy
Output of Real numbers

9/25/2022 Ref: Programming in ANSI C by 33


E.Balagurusamy
Output of Real numbers
⚫ Some systems also support a special field
specification character that lets the user define the
field size at run time. This takes the following form:
printf("%*. *f”, width, precision, number);

⚫ In this case, both the field width and the precision are
given as arguments which will supply the values for w
and p. For example,
printf("%*.*f ",7,2,number);
⚫ is equivalent to
printf (“%7.2f " ,number);
⚫ The advantage of this format is that the values for
width and precision may be supplied at run time, thus
making the format a dynamic one.
9/25/2022 Ref: Programming in ANSI C by 34
E.Balagurusamy
Output of Real numbers
⚫ For example, the above statement can be used as
follows:
int width = 7;
int precision = 2;
printf("%*.*P,” width, precision, number);

9/25/2022 Ref: Programming in ANSI C by 35


E.Balagurusamy
Printing of a Single Character
⚫ A single character can be displayed in a desired
position using the format:
%wc
⚫ The character will be displayed right-justified in the
field of w columns. We can make the display left-
justified by placing a minus sign before the integer w.
The default value for w is 1.
⚫ Printing of Strings The format specification for
outputting strings is similar to that of real numbers. It is
of the
⚫ form
⚫ %w.ps where w specifies the field width for display
and p instructs that only the first p characters of the
string are to be displayed. The display is right-justified.
The following examples show the effect of variety of
specifications in printing
9/25/2022 a string
Ref: Programming in ANSI"NEW
C by DELHI 36
E.Balagurusamy
Printing of Strings
⚫ The format specification for outputting strings is similar
to that of real numbers. It is of the form
%w.ps
⚫ where w specifies the field width for display and p
instructs that only the first p characters of the string
are to be displayed.
⚫ The display is right-justified. The following examples
show the effect of variety of specifications in printing a
string "NEW DELHI 110001", containing 16 characters
(including blanks).

9/25/2022 Ref: Programming in ANSI C by 37


E.Balagurusamy
Printing of Strings

9/25/2022 Ref: Programming in ANSI C by 38


E.Balagurusamy

You might also like