Freshers Resources

QA & Testing

Data WareHousingComputer ScienceAnalysis  DesignOperating Systems
C++MainframesSap/AbapDatabasesHRVB
JavaJobsC#

.Net

VC++ASP

Data Input And Output Function

For data input and output C provides a collection of library functions such as getchar, putchar, scanf, printf, gets and puts. These functions permit the transfer of information between the computer and standard input/output devices. Thestandard input and output devices like Keyboard and Monitor are treated as files by the UNIX system. UNIX is consistent in treating files, since it considers a file to be a stream of bytes. Text input or output, regardless from where it originates or where it goes to, is dealt with as stream of characters. A textstream is a sequence of characters divided into lines; each line consists of characters followed by a newline. All input or output functions conform to this model.


4.1PREPROCESSOR DIRECTIVE#include

The first two lines of the program in Example 1.1 contain following two statements.

# include

# include

Although those two lines look likeprogram statements, they are not part of a function body and do not end with a semicolon, as program statements must. Instead, they start with a hash sign (#), and are called preprocessor directives. While program statements are instructions to the computer, a preprocessor directive, is an instruction to the compiler itself. A part of the compiler called the preprocessor deals with these directives before it begins the real compilation process.

The preprocessor directive #include tells the compiler to insert another text file into your source file. In fact, the #include directive is replaced by the contents of the file indicated. The filenames stdio.h and math.h are examples of header files. These header files contain definitions of standard C utility programs and without these declarations the compiler will not allow the usage of commonly used standard input and output functions such asgetchar, putchar, scanf and printf, etc. The definitions of these functions are included in the stdio.h file. Thus reference to any such function inside the program requires the corresponding header file to be included using #include preprocesser directive. The symbols <>, that enquote the header filename indicates that the header file is located under /usr/include directory.



1. The _____________ is an instruction to the C compiler.

2. The symbols <>, which enclose stdio.h header file, indicate that the file is located under ______________directory.


4.2 THE SINGLE CHARACTER INPUT(getchar) AND OUTPUT (putchar) FUNCTIONS

The getchar and putchar are two standard library functions for reading one character at a time from a keyboard (standard input device such as keyboard) or writing a character to the monitor (standard output device e.g monitor). Each time the getchar function is called, it reads the next character from the

text stream and returns this character as its value. The character normally comes from the file associated with the keyboard.The function returns the symbolic constant EOF(for end of file) which typically stores the value -1, when there is no input. The EOF is an integer defined in stdio.h header file.

Example 4.1 :

#include

main()

{

char c;

c=getchar();

putchar(c);

}

The function putchar displays a character each time the function is called; it prints the content of integer c as a character, usually on the screen.

4.3THE scanf FUNCTION

The function scanf is used to input data from the standard input device. In general, the scanf function is written as

scanf(,arg1,arg2,....,argn);

where the refers to a string containing required formatting information and arg1, arg2, ..., argn are individual data items. Actually these arguments represent pointers that indicate the addressesof the data items in the computer’s memory.

One group of characters forms one control group for each data item in the list of arguments supplied to the scanf function. Each control group begins with the character percentage (%) followed by a conversion character which indicates the type of the corresponding data item. Similar control string is also used with the printf function to be discussed later. The meaning of the conversion characters for input /output is given in the table below,


Commonly used conversion characters for input/output:

Conversion

Meaning

Character

Input

Output

c

Data item is a single character

Displayed as a single character

d

Data item is a decimal integer

Displayed as a signed decimal integer

e

Data item is a floating point value

Displayed as a floating point value

f

Data item is a floating point value

Displayed as a floating point value (without exponent)

g

Data item is a floating point value

Displayed as a floating point value (with either e-type or f-type conversion depending on the value; trailing decimal point is not printed).

h

Data item is a short integer


i

Data item is a decimal, hexadecimal or octal integer

Displayed as a signed decimal integer.

o

Data item is an octal integer

Displayed as an octal integer without leading zero.

s

Data item is a string followed by a whitespace character (the null character ‘ \0 ’ is added at the end)

Displayed as a character string.

u

Data item is a unsigned integer

Displayed as an unsigned integer.

x

Data item is a hexadecimal integer

Displayed as a hexadecimal integer without leading 0x.

[]

data item is a string which may include whitespace characters


Table 4.1 : Conversion character set.

In scanf each variable name (not of pointer type) must be preceded by &. However array names or pointer data types must not begin with ampersand.

Example 4.2 :

# include

main()

{

charname[40];

int rollno;

floatgrade;

scanf(“%s%d%f”, name, &rollno, &grade);

}

Note the variable name being a string (an array of characters) is not preceded by &, but the numerical variables rollno andgrade are preceded by &. Whileproviding data values they must be separated by whitespace character e.g. blank, new line etc.

Formatted input

Example 4.3 :

# include

main ()

{

int x,y,z ;

float u,v,w ;

char a,b,c;

:

scanf (“%3d,%4f,%c”, &x, &u, &c)

:

}

If the data items provided are 10540.36A, then the variablesget valuesx = 105,u = 40.3,c = 6; note the character A is ignored. This is because the field width for u is 4 which can accommodate 40.3. The remaining character 6 is assigned to c.

3.Consider a C program with thefollowing declaration:

int i,j,k;

Write an appropriate scanf function to read i, j and k, assuming

a) The values of all of them aredecimal integers.

b) The values for ka decimal integer, i an octal integer and j a hexadecimal integer.

c) The values for i and j will be octal numbers and k will be an hexadecimal integer.

4. Interpret the meaning of the control string in each of the following scanf functions:

a) scanf (“%10d %3hd %14f”, &a, &b, &c);

b) scanf (“ %5ho %6hu%7tu”, &a, &b, &c);

c) scanf (“%10d %13f %16e”, &a, &b, &c);

d) scanf (“%7d %6d %10 lf”, &a, &b, &c );

5.Consider a C program havingthe following declarations:

int i, j;

long il;

short s;

unsigned u;

float x;

double d;

char c;

Write a scanf function for each of the following groups of variables that will allow a corresponding set of data items to be read into respective variables. Assume that all integers will be read in as decimal quantities.

(a) i, j,d and x(c) il, u,s and c

(b) i,j, x and u(d) c, d,and s

6.A C program contains the following variable declarations:

int i, j;

long il;

short s;

unsigned u;

float x;

double d;

char c;

Write a suitable scanffunction for reading data according to each of the following specifications. Assume that all integers will be read in as decimal quantities.

(a) Assuming that each integer data does not exceed five characters, the floating -point data does not exceed eight characters, and the double-precision data does not exceed 16 characters, enter values for i, j, x and d.

(b) The values fori, il, j, x and u are to be entered, assuming that each integer quantity does not exceed four characters, the long integer does not exceed 18 characters, and the floating-point data does not exceed 9 characters.

(c) The values for i, u and c, are to be read assuming that each integer data does not exceed five characters.

(d) The values for c, x, d and s,are to be read assuming that the floating-point data does not exceed eight characters, the double-precision data does not exceed 16 characters and the short integer does not exceed four characters.

7.Consider a C program with the following declarations.

int a, b;

float x, y;

Suppose the following values are to the entered and assigned to a, b, x and y respectively.

16,-43, 6. 391, - 43 ´ 107

Show how the input data shouldbe entered foreach of the following scanf functions.

a) scanf (“%d %d %f %f”, &a, &b, &x, &y);

b) scanf (“%d %d %e%e”,&a, &b, &x, &y);

c) scanf (“%3d %3d %6f %7e”, &a, &b, &x, &y);

d) scanf (“%2 d %3d %7f %8e”, &a, &b, &x, &y);

4.4THE printfFUNCTION

This function is used to output data onto a standard output device.

The syntax is

printf (, arg1,arg2,.... argn);

where the meaning of the control string is the same as in scanf.However, unlike scanf, the variable names in arg1,...........,argn are not to be preceded by the & symbol.This is because printf is expected to only output the values of these variables and not to modify their content.

Example: 4.4 :

a>

# include

main()

{

printf(“Our first program in C\n”);

}

b>

# include

main()

{

int n;

n=25;

printf(“The value of n = %d\n”,n); /* note usage of format specifier */

}

c>

# include

main()

{

int n;

printf(“Give an integer :”);

scanf(“%d”,&n);/* note usage of & before n */

fflush(stdin);/* flushes the stdin buffer */

printf(“The integer read is %d\n”,n); /* note no & symbol is present */

}

d>

# include

main()

{

float x = 2.0;

inty = 4;

charc = ‘A’;

printf (“%f%d%c\n”, x,y,c);

}

The printf statement given above will print the data values x, y, and c as follows,

2.0000004 A

followed by a blank line(due to \n).

This printf statement has the disadvantage that it may cause output values to be printed without any intermediate spaces. To introduce blank spaces in between the output values use the following printf statement which include blanks in the control string.

printf(“%f %d %c \n”, x,y,c).

Note that unlike in scanf, the variables in the printf statement are not preceded by the & character.

Formatted output.

The following printf statement can be used to print data values according to a specific format,

printf (“%6.2f%2d %c \n”,x,y,c);

If x,y and c had values 453.7869, 243 and B assigned to them respectively, this printf statement will print 453.79, 243 and B.Note that due to the precision specification the floating point variable has been rounded to fit the specified field width.Leading blanks may be introduced to fill the minimum field width (usually 7 character). Since the field width specified for y is too small 2d as compared to the specified field width supported for integer data items (e.g. 8 digits). The entire integer value would be displayed preceded by leading blanks to fill the specified width.

Here is a program that illustrates the use of precision feature with floating point numbers. The character ‘*’ in the format specification helps in understanding the width of the display.

Example 4.5 :

# include

main()

{

float f=123.456;

printf(“*%f*\n”,f);

printf(“*%15f*\n”,f);

printf(“*%-15f*\n”,f);/* ‘-’ character changes the default alignment*/

priintf(“*%2f*\n”,f);

printf(“*%.3f*\n”,f);

printf(“*%.1f*\n”,f);

}

The above program displays the following output :

*123.456000*

*123.456000*

*123.456000*

*123.456000*

*123.456*

*123.5*

8.A C program contains the following declaration:

int i, j, k;

Write a printf function for printing each of the following groups of variables or expressions.

(a) i, j and k,with a minimum field of four characters per variable.

(b) (i + j), (i - k), with a minimum field width of six characters per expression.

(c) sqrt (i / j), abs (i * k), with a minimum field width of eight characters for the first expression and eight characters for the second expression.

9.A C program contains the following declarations:

int i, j, k;

Write a printf function for displaying each of the following groups of variables or expressions.

(a) i, j and k(b) (i + j), (i *- k)(c) sqrt(i / j), abs(i - k)

4.5SAMPLE C PROGRAMS

The following examples illustrate the different ways to input a string of characters and to display them.

Example 4.6 :

a>

/* program takes string as input */

# include

main()

{

char anyname[21];

printf(“Enter your name :”);

scanf(“%s”,anyname);/* Note that a string variable does not need to be prefixed by ‘&’ symbol */

fflush(stdin);

printf(“%-20s”,anyname); /* ‘-’ before 20s in format specification prints name left justified within 20 characters long width */

}

In the above example if the name is entered with embedded space then the variable anyname will be assigned with all characters till the space, since space will terminate the input stream. In this example, if input given is,

Satyen Bose

then anyname gets “Satyen” only.

b>

# include

main()

{

char in_string[80], out_string[80]=“IIT-Dedicated to the Service of The Nation”;

printf(“Enter a string :”);

scanf(“%[^\n]s”,in_string); /* Statement A */

fflush(stdin);

printf(“Enter a string :”);

scanf(“%[ABCEFGHIJKLMNOPQRSTUVWXYZ]s”,in_string);

/*statement B*/

fflush(stdin);

printf(“*%s*\n”,out_string);

printf(“*%20s*\n”,out_string);

printf(“*%10.3s*\n”,out_string);

printf(“*%-10.3s*\n”,out_string);

printf(“*%.3s*\n”,out_string);

}

In the above program, the statement A will allow input of any characterexcept the newline character (\n). The ^ symbol before ‘\n’ indicates that the input stream will be terminated as soon as the user presses the enter key. Most importantly, the user can also input embedded spaces. The statement B allows input of capital alphabets and spaces only. A preceding ^ in the format specification would have restricted the input to the characters other than specified within the square brackets. The format specification used with the printf statements that follow will display the following strings on the screen.

*IIT-Dedicated to the Service of The Nation*

*IIT-Dedicated to the Service of The Nation*

*IIT*

*IIT

*IIT*

Example 4.7 :

/*A program to convert temperature in Centigrade to Fahrenheit and vice versa*/

# include

main()

{

float c,f,ic,fi;

printf(“Enter temperature in Centigrade :”);

scanf(“%f”,&c);

fflush(stdin);

printf(“The temperature in Centigrade is : %5.1f\n”,c);

/* the above statement prints the input in 999.9 format */

f=1.8 * c + 32;

printf(“\nThe Fahrenheit equivalent of Centigrade %5.1f is : %5.1f\n”,c,f);

printf(“Enter temperature in Fahrenheit :”);

scanf(“%f”,&fi);

fflush(stdin);

printf(“The temperature in Fahrenheit is : %5.1f\n”,fi);

/* the above statement prints the input in 999.9 format */

ic=(fi - 32)/1.8;

printf(“\nThe Centigrade equivalent of Fahrenheit %5.1f is : %5.1f\n”,fi,ic);

}

4.6THE gets AND puts FUNCTIONS

The standard library function gets (defined in header file stdio.h) in C accepts input in the form of a string including any whitespace character. Recall that thescanffunctionterminates input when it encounters whitespace character in the input stream. The putsdisplays the string on the monitor. Unlike printf which inserts a newline at the end of display only if ‘\n’ is explicitly specified in the control string, puts after displaying a line takes the cursor to the next line automatically. The function puts can only handle one object as parameter.The following example illustrates the usage of gets & puts function.

Example 4.8 :

# include

main()

{

char inp_line[81];

printf(“Enter a line of text that may include embedded spaces : \n“);

gets(inp_line);

fflush(stdin);

puts(“The line entered is :”);

puts(inp_line);

}

10.A C program contains the following declarations:

int i, j;

long il;

unsigned u;

float x;

double d;

char c;

With the help ofprintf function display the data values mentioned for each of the following cases.

(a) Displaythe values ofi, i%j, x and d, assuming that each integer quantity will have a minimum field width of six characters and each floating point quantity is to be displayed in exponential notation with a total of at least 12 characters and no more than eight decimal places.

(b) Repeat part (a), displaying the integer and floating point variables inseparate lines.

(c)Display the values of i, il, u, x and d - j * x, assuming that each integer datawill have a minimum field width of six characters, the long integer will have a minimun field width of 10 characters, and the floating point quantity will be at least 8 characters with a maximum of five decimal places.

(d) Repeat part (c), displaying each variable in separate lines.

(e) Print the values of i and c, in separate lines with a minimum field width of six characters for each integer data. Introduce three blank spaces between the lines where values of i and c are displayed.

(f) Repeat part (c) with a sign (either + or -) preceding each signed data item.

(g) Repeat part (v) by filling out the field for each of the integer data with leading zeros.

11.A C program contains the following variable declarations:

float a =14.5, b = 0.00004, c = 9060.;

Show the output resulting from each of the following printf statements:

(i) printf (“ %f %f %f”,a,b,c);

(ii)printf (“%2f %2f %2f”, a,b,c);

(iii)printf (“%7f%7f %7f”, a,b,c);

(iv)printf (“%7.4 %7.4 %7.4”, a,b,c);

(v)printf (“%e %e %e”, a,b,c);

(vi)printf (“%4e % 4e %4e”, a,b,c);

(vii)printf (“%10e %10e %10e”, a,b,c);

(viii) printf (“%`10.5e % 10.5 % 10.5”, a,b,c);

(ix)printf (“% -7f %-7f %-7f”, a,b,c);

(x)printf (“%+7.2f%+7.2f % +7.2f ”,b,c, b + c);

(xi)printf (“ % 07f”, a * b);

(xii)printf (“%# 6f % #6f”, a,b,);

(xiii)printf (“% g % g ”, a,b);

(xiv)printf (“% #g % #g %#g”, a,b/c,c);