You are on page 1of 10

Input and Output in C

Part – 2

Module – 1

Welcome to the second module on input and output in C. In the previous module we
learned about the input operations in C, and got a hang of the output operations
possible. In this module we will learn about the standard output operations in detail.
Other than the standard input and output library (or STDIO) that comes with all C
compilers, we will also briefly discuss one library called the console input/output
(CONIO) library that is provided with the Turbo C development system. This library
extends the functions provided in STDIO to include screen management operations
for text-based output.
Character output
In the last module we saw how putchar() function is used. It is the fundamental
output mechanism in C. The prototype is int putchar(int). It takes one integer
argument, and outputs the corresponding character on the standard output device,
that is the monitor by default. This function also returns an integer value. This return
value is used to test whether the output was successful or not. If the output was
successful, then putchar returns the character that was displayed. If there was an
error during the output, then putchar returns the End-Of-File or EOF character, that
is -1 on most of the systems.

Module – 2
Formatted output using printf
In many programmes we need to output numbers, character strings and many other
kinds of data. Such output is called formatted output and we have already come
across a powerful function that handles such outputs. It is called printf. Let us see an
example.
int a; /* simple integer type */
a = 100;

1
printf("a = %d\n",a); /* decimal output */
We have seen this kind of output statements before. Here, the ‘%’ symbol tells the
programme that we are not trying to display a character string as it is, as we do in a
statement like printf(“Hello world”). % is a special character that marks the start of a
variable. Here we have the character ‘d’ following the % sign, which tells the
programme to get a decimal value and print it on the screen. This decimal value is
available as the next parameter to the printf function. In this case, it is the value of
the integer a. In the first parameter, we have a ‘\n’ after the d, which means the
display cursor should go to a new line and come to the beginning of that line.
We get “a = 100” at the screen, and the cursor goes to the beginning of the next line.
Note that the characters between the quotation marks in the first parameter define
the pattern, or format, in which the data is to be output by this statement. After the
pattern, there is a comma, followed by the variable name that appears as the second
parameter. printf converts this integer into decimal format before displaying it. It is
possible to have more %ds in the first parameter, indicating that there are more than
one values to be printed. In that case, the function would expect more parameters so
that it gets all the values to be printed. For example, the programme segment
int a, b;
a = 100; b = 25;
printf("a is %d and b is %d\n", a, b);

displays “a is 100 and b is 25” on the screen, and the cursor goes to the next line.
It is important that the number of field descriptors and the number of variable
definitions must be the same, and the types should match.
Some other valid characters that can follow a % sign in the first parameter are ‘o’ for
octal notation, ‘x’ for hexadecimal, ‘u’ for unsigned, ‘c’ for character, ‘s’ for string and
‘f’ for floating point notation. For example, the statements

int a;
a = 100;
printf("a in octal notation is %o\n",a);
cause the programme to display “a in octal notation is 144” on the monitor, because
one four four is the octal notation of the number hundred. Similarly,
int a;

2
a = 100;
printf("a in hexadecimal notation is %x\n",a);
prints “a in hexadecimal notation is 64”. Note that 100 is six times sixteen plus 4.

char c;
int a;
c = getchar();
scanf("%d", &a);
printf("c is %c and a is %d\n", a, c);
prints “c is”, space, the value of character c (read from the keyboeard), space, “and
a is”, space, followed by the value of integer a that the programme reads in from the
keyboard.
char name[100];
int marks;
scanf("%s %d", name, &marks);
printf("Name : %s, Marks : %d \n", name, marks);
prints the name, that is a character string without any space in between, and the
corresponding marks, that is an integer, that is input using the scanf statement from
the keyboard.
For example, if the user entered the name Vijay and the number 98, we get
Name : Vijay, Marks : 98
on the computer's display.
Between the percentage sign and this character that denotes in what notation the
variable should be displayed, we can have one of the following fields if necessary. A
‘-‘ indicates it needs to be left justified, a number specifying the minimum field width,
and another number following a decimal, to specify the number of fractional digits to
display for a floating point number. Here are some more examples.
float num; /* floating point type */
num = 3.1415
printf("num is %f\n", num); /* simple float output */
This prints “num is 3.1415” on the computer screen.
printf("num is %12f\n", num); /* use field width of 12 */
here the display uses a field width of 12 for the field num. By default the display is
right justified. It means that it prints “num is”, followed by some blank spaces, and

3
then the number 3.1415, so that the total width used up by the variable 'num' is 12
characters.
printf("num is %12.3f\n", num); /* field width 12 and 3 decimal places */
this prints only the first three decimal places, that is “num is”, then blank spaces,
then “3.141”.
printf("num is %-12.5f end\n", num); /* left justify the variable */
prints five decimal points and left justifies the number. It prints “num is”, then the
number 3.14150, and then blanks to fill the width of 12, and then the word “end”,
followed by a line break.
%f can be used for 'float' (that is a floating point number) as well as 'double' (or
double precision floating point number) types of data. See one example.
double num1; /* double precision floating point type */
num1 = 3.141496784;
printf("num1 is %f\n", num1); /* double precision float output */

Module – 3
Printing Character Strings

The printf can also be used to output character strings. %s is used to denote a string
variable. The following statements indicate the different forms of output possible
when the printf function is used with character strings. Here also we can use ‘-‘ sign
as well as numbers between the percentage symbol and ‘s’ in order to specify how
the string variable should get displayed. The usage is similar to the usage in printing
the floating point numbers.
For example, if the string variable “line” was assigned the value “Indian Democracy”,
it can be displayed in various ways as follows.
printf("begin %s end", line);

prints “begin Indian Democracy end”.


The statement
printf("begin %10s end", line);

4
also prints the same, “begin (space) Indian (space) Democracy (space) end”. This is
because the width field makes sense only when the width is more than the actual
width of the string variable. Here the string is more than ten characters long, so
applying a width of 10 does not make sense for this field. But if we write

printf("begin %.10s end", line);


it prints “begin Indian Dem (space) end”. The number after the decimal point is an
indication that the string should be trunctated to that many characters if the length is
more than that number. If this number is more than the length of the string, it does
not do anything. For example,

printf("begin %.20s end", line);


displays “begin Indian Democracy end”, because the string length is more than 20.

In contrast to this, the number before the decimal starts making sense when it is
more than the actual length of the string. This width field is particularly useful when
we are printing the contents of a table.

printf("begin %20s end", line);


prints “begin (some spaces) Indian Democracy (single space) end”, so that the string
field is of width 20 characters. A '-' can be used to left justify this display. For
example,

printf("begin %-20s end", line);


prints “begin Indian Democracy (then some spaces) end”. Here also the striing field
is of width 20 characters, but the string appears left justified. We can also use both
the numbers together as we did with the floating point numbers.

printf("begin %20.10s end", line);

prints “begin (spaces) Indian Dem end”. Similarly,

printf("begin %-20.10s end", line);

prints “begin Indian Dem (then some spaces to fill the width) end”.

Note that the printf function uses its first argument to decide how many arguments
follow and what their types are. The programme will not behave as expected, if the

5
actual number of arguments is less than what is specified, or if they are of wrong
type.

Puts function
We can use the function puts to output a line of text on the screen. Like gets, puts
also has the potential danger that it could corrupt the memory and it could even lead
to a crash. It is safer to use putchar in a loop instead.

Internal data formatting


There are times when we are not really interacting with the outside world, but some
input/output functions will come in handy in manipulating data internally. sprintf and
sscanf are two functions that help us in such situations. The function sprint acts just
like a normal printf function except that instead of printing the text output to a device,
it prints the formatted text output to a character string in memory. Similarly, sscanf
reads from an address in the computer’s memory. See this example for an
illustration.
void main( )
{
int num1, num2, num3, num4;
char line[80];
num1 = 74;
num2 = 18;
sprintf(line, "%d %d \n", num1, num2);
printf("%s", line); // prints “74 18”
sscanf(line, "%d %d", &num3, &num4);
printf("num3 is %d and num4 is %d\n", num3, num4);
}
First we declared four variables, then assigned values to num1 and num2. sprintf
behaves like a normal printf, but keeps the formatted output in the string “line”
instead of displaying it on the standard output. sscanf reads from the string variable
“line” that is still in the computer’s memory, just like reading from the keyboard input,
and assigns values to num3 and num4.

6
It is possible to read data from an input device using any of the standard functions
and then do a format conversion in memory using these functions.
Standard error output
Sometimes we may want to redirect the output from the standard output device to a
file. However, you may still want the error messages to appear on the monitor. We
now see an example that shows how to achieve this.
#include "stdio.h"
void main( )
{
printf("Message for the standard output.\n");
fprintf(stderr,"Message for the error device.\n");
}
The program consists of two output statements, one to the standard output device
and the other to the standard error device. The message to the standard error
device is output with the function fprintf and includes the device name stderr as the
first argument. We will see the function fprintf in detail in a later module on file
operations.
If we compile and run this program, and it prints both the lines of output on the
monitor, because it doubles up as standard output device as well as the standard
error device. But if we run the program again, this time redirecting the output to a file
named ‘outfile’, that is,
prog > outfile
This time it prints only one line of output to the standard error device, that is the
monitor, and it creates a file named ‘outfile’ containing the other line, the line meant
for the standard output device.

Module – 4
Other input/output libraries
The user experience is important if we are designing a commercial software. As we
mentioned in the beginning, the ANSI standard for C does not define any text screen
or graphics functions, mainly because the hardware environments are not standard.
However, Turbo C provides extensive screen and graphic support libraries for the

7
PC environment. The use of these libraries, or other third-party library systems, can
enhance the user interface created by programmers. Because the libraries are non-
standard, the programs that make use of them are not portable to other platforms.
The prototypes and header information for the text-screen handling functions are
stored in the conio.h file, and the prototypes and related information for the graphics
system are held in the graphics.h file in Turbo C.

Some functions in CONIO.H

We will briefly discuss some functions available in conio library, that helps to improve
the standard output produced by C programs. As we mentioned, these functions are
not standard, and hence they are supported only in the Turbo C environment. Also,
because these functions are not built on top of the input and output functions
provided by the standard library, and hence it will not work as expected if we try to
redirect the input from a file instead of from the keyboard, or if we redirect the output
to a file instead of the monitor.

The function clreol does not take any arguments, and it clears the screen from the
current cursor position to the end of the line in the active text window. The cursor
position remains unchanged. This function does not return any value.

clrscr() is another commonly used function. It does not take any arguments, and
clears the entire active text window and locates the cursor in the upper-left corner.
The colour of the window is set to the current textbackground colour.

The delline() function deletes the line in the active window that contains the cursor.
All lines below the deleted line are moved up to fill the gap and a blank line is
inserted at the bottom of the window.

gettext() is an input function. The prototype is int gettext(int, int, int, int, void*). The
first four parameters are the left, top, right and bottom co-ordinates of a rectangle
respectively. This function copies the text from this rectangle into the buffer pointed
to by fifth parameter. The coordinates are absolute screen coordinates, not the
window co-ordinates. The function returns a 1 if the action was successful, 0 on
failure.

8
gotoxy() is a function that two integer parameters x and y, and sends the text screen
cursor to the location specified by x,y. If either or both of the coordinates are invalid,
it does not do anything. This function does not return any value.

textbackground() and textcolor() are two functions that take a color number as input.
The first function sets the text background color, and textcolor() sets the text color, of
a text screen.

For more functions available in conio.h, you should refer to a documentation of the
conio library.

Summary
The Input and Output section (Part – 2) describes about the standard output
operations in C.

This section briefly discusses about the standard input and output library (STDIO)
and the console input/output library (CONIO) that is provided with the Turbo C
development system. CONIO library extends the functions provided in STDIO to
include screen management operations for text-based output.

In C programming, the function printf is used to output numbers, character strings


and many other kinds of such formatted data. It is the standard output function in C.
Data format conversion using printf function is detailed here with examples. ‘puts’
function output a line of text on the screen. sprintf and sscanf are the internal data
manipulating functions.

The conio library functions such as clreol, clrscr , delline , gettext , gotoxy ,
textbackground, textcolor etc are also discussed in this section in details.

Exercise Questions
1. Write a program that formats a floating point number into a string that
contains the number in a currency format. For example, the number 23456.78
would be converted into the string “$23,456.78”.
2. Use the sscanf function to convert a date in the form of “dd/mm/yy” into the
respective integers representing day, month and year.
3. Consider the following two statements:
printf(s);
printf("%s",s);
If s is a character string, are these two statements equivalent? If not, in what
cases do they give different outputs? Why?

9
4. Assume that a variable ‘num’ contains the number 2.17165. Find out what will
be the output of the following statements.
printf("begin %f end", num);
printf("begin %10f end", num);
printf("begin %.10f end", num);
printf("begin %.20f end", num);
printf("begin %20.4f end", num);
printf("begin %-20.7f end", num);

References

1. B. W. Kernighan and D. M. Ritchie, The C Programming Language,


Prentice-Hall, Englewood Cliffs, New Jersey, 1978.

2. Yashavant Kanetkar; Let us C, BPB Publications, New Delhi.

3. Greg Perry, Absolute Beginners' guide to C, SAMS publishing, April


1994.

4. Turbo C documentation.
Link : http://www.iu.hio.no/~mark/CTutorial/CTutorial.html

10

You might also like