Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Chapter 5

C input/output functions
C Standard Library
 To make a language simple, functionality is usually provided in a library along
with the language compiler.
 The functionalities include data types, input/output, control structures, user-
defined functions, arrays, pointers, structures, strings etc.
 Header files
 The library can be subdivided into several categories which is provided in
separate text files called header files.

Category Header File Functions

Input/output stdio.h scanf, printf, getchar, putchar,


gets, puts
Mathematical math.h sqrt, sin, cos, log, pow
String manipulation string.h strcpy, strcat, strlen, strcmp
character test ctype.h isalpha, isupper, toupper
utility operations stdlib.h exit, rand, abs
Input and output functions
 A function is a named block of code.
 It has a reusable property, i.e. it can be executed from
different points in a C Program as and when required.

 In a programming language we need means to input


some data into a program and means to output data on
a monitor, printer, file etc.
 C programming language provides a set of built-in functions
(Input functions) to read given input and feed it to the
program as per requirement.
 Similarly it provides a set of built-in functions (Output
functions) to output required data.
Buffered Input/output
 Data read from a keyboard is stored as a block of data in a buffer called
input buffer.
 Similarly, data is written into an output buffer, which when it
becomes full, a block of data is written onto the Output device making
the buffer empty.
Input
Buffer Data
Block of data

Stream
I/O Devices

Block of data Data


Output
Buffer
I/o Streams
When the header file stdio.h is included in a program, the following standard
stream pointers are automatically opened:

Name Meaning
stdin standard input
stdout standard output
stderr standard error
stdaux auxiliary storage
stdprn printer

 In the computer, 'stdin' and 'stdout' refer to the user's input device such
as keyboard and output device as VDU (screen).
The stream pointers 'stdprn' and 'stdaux' refer to the printer and auxiliary
storage, respectively.
The error messages generated by the stream are sent to standard error
(stderr) stream.
Classification of Input/output functions
We have to include the following statement to use the I/O functions
#include<stdio.h>

Input/
output
functions

Unformatted Formatted

getchar() putchar() gets() puts() scanf() printf()

CHAPTER HOME SLIDE


Unformatted I/O Functions
 The unformatted functions can be further classified
 1. Character Based
 As the name suggests these functions can read or write one
character at a time.
 E.g. getchar() putchar()
 2. String Based
 These functions can read or write a string of characters at a
time.
 E.g. gets() puts()

Unformatted functions for


char data type only.
getchar() and putchar() functions
 getchar()
 The getchar() function reads a single character from the
standard input device.
 To read a character from the keyboard into a character
variable ch, the statements are
 char ch;
 ch = getchar(); note there are no argum ents
to the getchar function
 putchar()
 The putchar() function is used to send a single character to
the output device.
 To write a character variable ch onto the screen, the
statements are
 char ch =‘b’; see that only a single w rong assignm ent
 putchar(ch); character constant is char ch = “b”;
assigned to the character
variable ch
gets() and puts() functions
 gets()
 The gets() function reads a string of characters from the
standard input device.
 To read characters from the keyboard into a character array
named city, the statements are
 char city[]; Also one has to hit the
 gets(city); enter key to terminate
the input string.
 puts()
 The puts() function is used to send a character string to the
output device.
 To write a character string city onto the screen, the statements
are
 char city[] =“mangalore”; wrong assignment
 puts(city); char city[]=‘mangalore’;
Formatted I/O Functions
 Formatted I/O functions refers to the conversion of
data to and from a stream of characters, for printing
(or reading) in plain text format.
 These functions can read and write all data types.
 The formatted I/O functions in C are
 scanf() : which reads from standard input.
 printf() : which writes into standard output.

Printf() is not the same as printf()


Likewise for scanf().
Conversion specifiers in C
 A conversion specifier is a symbol that is used as a
placeholder in formatting a string.
Conversion Character Data type
d int
f float
c char
s string
u unsigned decimal integer
x hexadecimal
h short integer
lf double
lu long unsigned
scanf()
 scanf() is a formatted standard input function.
 The basic syntax( format) of scanf() is

scanf(“ control string”, &arg1,&arg2,…….,&argn);

control string consists of


 The conversion character % along with the desired
format specifier character.
 arg1,…..,argn represents the address locations of variables
 E.g int age;
 float gpa;
 scanf(“%d%f”,&age,&gpa); No comma between %d
and %f
scanf()
 Double quotes should enclose the control string and comma should
separate it from argument section.
scanf(‘%d” ,&age);

scanf(“%d” &age);

 The address & operator in scanf() function is mandatory.


scanf(“%d” ,age); scanf(“%d” ,&age);
 But in case of strings we do not use the & operator.
scanf(“%s” ,&name);

scanf(“%s” ,name);
 Also the character is case sensitive and there should not be any
space in between % and the character.

scanf(“%D” ,&age); scanf(“% d” ,&age);


printf()
 printf() is a formatted standard output function.
 The basic syntax( format) of printf() is

printf(“ control string”, arg1,arg2,…….,argn);

 control string consists of


 The statement which is to be displayed on the standard
output ( Usually the monitor).
 The conversion character % along with the desired format
specifier character.
 arg1,…..,argn represents the address locations of variables

 For the previous variables the printf() statements can be:


 printf(“ The age of the student is = %d “, age);
 printf(“ The gpa of the student is = %f “, gpa);
printf()
 There is no & operator in printf() function.

printf(“ the age of the student is = %d”,&age);

printf(“ the age of the student is = %d”,age);

 Double quotes should enclose the control string and comma should
separate it from argument section.
printf(‘the age of the student is = %d”,age);

printf(“the age of the student is = %d” age);


 The Conversion character % should be used in case of arguments with
the proper conversion specifier.
printf(“the age of the student is = d”,age);

printf(“the age of the student is = %c”,age);


Escape sequence characters
 Character combinations that comprise a backslash (\)
followed by some character.
 They are called escape sequences because the backslash
causes an "escape" from the normal way characters are
interpreted by the compiler.
Escape sequence Meaning
\n New line
\t Horizontal tab
\r Carriage return
\b Backspace
\’ Single Quotation Mark
\” Double Quotation Mark
\\ Backslash
Note
 scanf() function returns the number of successfully
read items.
 printf() functions returns the number of characters
successfully printed.
We can print multiple printf() statements
using a single printf() statement.

The two C statements


printf(“ The age of the student is = %d “, age);
printf(“ The gpa of the student is = %f “, gpa);

The combined statement is


printf(“ The age of the student is = %d and gpa is =%f“, age, gpa);
Common errors
 int a =10, b =20;
 float x= 1.2;
printf(“%d%d\n”,a,b,a+b); Extra argument expression (a+b)

printf(“%d%d %d\n”,a,b); Extra format specification

printf(“%d %f\n”,x,a); Type mismatch

For the above 3 cases, does the C compiler give any warning or error ?
Most of the old version compilers do not generate any error/warning.
And it may give erroneous output for all/some of the cases which differs based
on the compiler and version.

We can have printf statements without arguments if we want to display


a message.
printf(“ Please enter the name and age of the student”);
Field width specifiers for printf()
 In order to display output that occupies a certain
number of spaces on the screen we add an integer
value after the % of a format specifier.
 For E.g.
- symbol means left justified
 int x = 123 ;
Statement Output
printf(“%%d displays %d\n", x); %d displays 123
printf(“%%3d displays %3d\n", x); %3d displays 123
printf(“%%4d displays %4d\n", x); %4d displays 123
printf(“%%04d displays %04d\n", x); %04d displays 0123
printf(“%%06d displays %06d\n", x); %06d displays 000123
printf(“%%-6d displays %-6d\n", x); %-6d displays 123
Field width specifiers cont…
 In case of floating point variable we use the format:
W= field width of the characters
W. P
P = Number of digits after the decimal point

E.g float x = 3.14264;

Statement Output
printf(“%%f displays %f\n", x); %f displays 3.14264
printf(“%%3.2f displays %3.2f\n", x); %3.2f displays 3.12
printf(“%%4.3f displays %4.3f\n", x); %4.3f displays 3.142
printf(“%%4.1f displays %4.1f\n", x); %4.1f displays 3.1
Field width specifiers cont…
 In case of string variable we use the format:
W= field width of the characters
W. P
P = First P characters to be displayed

E.g char name[] = “New Delhi”;

Statement Output
printf(“%%s displays %s\n",name); %s displays New Delhi
printf(“%%5s displays %5s\n“,name); %5s displays New Delhi
printf(“%%.5s displays %.5s\n",name); %.5s displays New D
printf(“%%12s displays %12s\n“,name); %12s displays New Delhi
printf(“%%12.5s displays %12.5s\n“,name); %12.5s displays New D

HOME SLIDE
 scanf() terminates at the encounter of blank space.
i.e if we want to input the string str “new delhi”
scanf(“%s”,str); // only new is accepted.

In order to overcome this drawback we use the


scanf(“%[^\n]”,str); // now new delhi is accepted.

observe the conversion specifier s is not used.


Also till the user hits the enter key, the string is accepted.

One can also use the gets() function to achieve the same feature

 Field width specifiers are not generally used with scanf()


function cause the outcome could be error ridden.
Incorrect format specifeirs should not be used with both printf() and scanf().
scanf(“%k”,&age); // invalid type specifier k
printf(“%a”,age) // invalid type specifier a
<ctype.h> functions
 This header file consists of character handling functions.
 The most commonly used functions in this header file are:
 islower()
All these functions use a character
 isupper() variable as an argument
 tolower()
For E.g. char ch;
 toupper()
islower(ch);
 isalpha() isdigit(ch);
 isdigit()
 isalnum()
• The return value of the above functions is either False (0)
or True (non zero character).
What are header files in C ?
Explain with syntax and an example the functions
 getchar() putchar()
 gets() puts()
What are formatted input/output functions ?
 Explain the following with respect to I/O functions
 Conversion specifier
 Escape sequence characters
 Field width specifier

You might also like