Vous êtes sur la page 1sur 8

Using the C Standard Library Functions

The Standard Input and Output (I/O)

A computer treats data as a series of bytes called a stream. It can read data from a hard
disk or from a floppy or the keyboard. Each of these sources of data represents a different
stream. A stream in C language is a variable of the type FILE. You will learn about this
type of variable in detail in the second part of this course (Computer Science B).

§ The standard input stream for reading is stdin. It is normally associated with the
keyboard.
§ The standard output stream for writing is stdout, which is usually the screen.

C language provides many functions to manipulate data reading and writing. The header
file stdio.h contains the declarations for these functions.

The header file stdio.h must be included in any C program that uses Input /
Output.

Writing to the Standard I/O

We have already used the printf() function in the previous tutorials to write text,
characters and numbers onto the screen. An argument of the printf() function consists of
a formatting string that may contain format specifiers, and expressions to be formatted.

Each format specifier must have a corresponding expression. The following format
specifiers can be used in the printf() function:

%c The character format specifier.

%d or %i The integer format specifier.

%f The floating-point format specifier.

%e or %E The scientific notation format specifier.

%g or %G Uses %f or %e (%E), whichever result is shorter

%o The unsigned octal format specifier.

%s The string format specifier.

%u The unsigned integer format specifier.


%x or %X The unsigned hexadecimal format specifier.

%p Displays the corresponding argument which is a pointer.

%% Outputs a percent sign (%).

The format specifiers %d, %f, and %c were introduced in the previous section. The use
of some others will be discussed later. To print long or double value, the letter l is to be
added to the format specifier: %ld, or %lf. You can experiment with format specifiers to
find out the way they output an expression.

The format specifiers allow you to print the output in a particular manner by writing some
additional formatting characters between the percent sign % and the letter.

Setting the minimum field width.

The minimum field width can be set by writing an integer number. For example

int n1 = 5;
int n2 = 5432;

printf("%d\n", n1);
printf("%d\n", n2);
printf("%4d\n", n1);
printf("%04d\n", n1);
printf("%2d\n", n2);

Output:
5
5432
5
0005
5432

• The first two lines are printed without any minimum field width specifiers.
• The minimum width of 4 is set in the third line for the number n1 (%4d), which
results in 3 white spaces being added in front of the number.
• The specifier %04d in the next line replaces white spaces with zeros.
• Note that the format %2d for n2 in the last line sets the minimum width which is
smaller than the width of the output. In this case the minimum width is ignored
and the number is printed in full.

Aligning output

The output can also be aligned to the left or right. By default the output has right
alignment, as in the example above. To specify left alignment include a minus sign in front
of the minimum field width,
like in (%-4d)

Specifying precision

For a floating point number you can set the precision or number of decimal places to be
printed. The precision specifier consists of a dot and the following integer number. For
example, printf("%.2f", 35.5678); will print 35.56. If you add a number and a sign
before the dot, you will specify the minimum field width and alignment together with the
precision. For example, the following two lines

printf("%-5.2f\n", 32.5678);
printf("%-5.2f\n", 3.333);
printf("%-5.1f\n", 2.0);

will output

32.56
3.33
2.0

Two other functions can be used to output characters onto the screen.

• The function int putc(int c, FILE *stream); takes two arguments, which are an
integer value for a character and a stream. To print the character onto the screen
the stream must be stdout.
• The function int putchar(int c); needs only one argument to represent a
character, because it always prints into the standard output.

The following program illustrates the use of these two functions.

Program 4.1.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
char c1 = 'H';
char c2 = 'e';
char c3 = 'l', c4;
char c5 = 'o';

c4 = c3;

printf("\n\nPrinting the output using the putc() function:");

putc(c1, stdout);
putc(c2, stdout);
putc(c3, stdout);
putc(c4, stdout);
putc(c5, stdout);

printf("\n\nNow printing the output in a column”):


printf(“ using the putchar() function:");

putchar(c1);
putchar('\n');
putchar(c2);
putchar('\n');
putchar(c3);
putchar('\n');
putchar(c4);
putchar('\n');
putchar(c5);
putchar('\n');
system(“PAUSE”);
return 0;
}

Output:

Printing the output using the putc() function:

Hello

Now printing the output in a column using the putchar()


function:

Reading from the Standard I/O

To read a user input from the keyboard (standard input) the following functions can be
used.

• The function int getc(FILE *stream) reads the input from the input stream. In
the case of the reading from the keyboard, stream is stdin. The function returns
an integer value corresponding to the character typed.
• The function int getchar() reads only from the standard input and returns an
integer value corresponding to the character typed. Both functions read one
character at a time.
• The function int scanf() can read an arbitrary number of characters from the
standard input file stdin and store them at the given addresses. The address of a
variable indicates the location of this variable in the computer memory. The
address-of-operator & returns the address of a variable.

The scanf() function has two arguments: control_string and list of addresses. For
example

int n;
float x;

scanf("%d %f", &n, &x);


printf("The numbers entered are %d and %f\n", n, x);

The control_string includes formats similar to the format specifiers in the printf()
function, which convert the input characters into the specified data types.
The scanf() function reads an input stream until the null or new -line character is
entered. The input values can be separated by the [TAB] or [WHITE SPACE]
characters. If the scanf() function concludes successfully it returns the number of
items read from the stdin. If an error occurs, the scanf() function returns a
constant EOF (end-of-file). This constant is defined in the stdio.h header file and
usually equals -1.

Good programming practice is to check the output of the sca nf() function
before using the values that have been read.

Program 4.2

#include <stdio.h>
#include <stdlib.h>

int main()
{
int num, count;
float fl_num;
char c, last;

printf("Enter one integer number, one floating-point number”);


printf(“ and one character.\n");

/*Read the input stream */


count = scanf("%d %f %c", &n, &fl_num, &c);
last = getchar();
if(count == EOF)
{
printf("Invalid input. The program is terminated.\n");
exit(1);
}
else
{
printf("You entered the following items: “);
printf(“integer %d, float %f, and character %c\n",
num, fl_num, c);
printf("The number of items read is %d\n", count);
printf("The last character read from the input stream”);
printf(“ has int value %d\n", last);
}
system(“PAUSE”);
return 0;
}

Output:

2 3.5 *
You entered the following items: integer 2, float 3.5 and character *
The number of items read is 3
The last character read from the input stream has int value 10

The last character in the input stream in the program above is nl or new-line character,
which is entered by pressing the [ENTER] key. Its integer value is 10.

NOTE that there are variables' addresses in the argument list of the scanf()
function. Writing, for instance, x instead of &x will result in a run-time
error.

Math Library Functions

The header file <math.h> contains prototypes of the mathematical functions in the
standard C library. All mathematical functions return double value and take variables of
the type double as arguments. Some of the useful mathematical functions are listed here.
The example of using sqrt() function is given below.

The Program 4.3 reads coordinates of two points on a plane from the keyboard and
calculates the distance between them using the following expression:

Program 4.3

#include <stdio.h> /*header file contains prototypes of the printf()


and scanf() functions*/
#include <stdlib.h> /*header file contains prototype of the exit()
function */
#include <math.h> /*header file contains prototype of the sqrt()
function */

int main(void)
{
double x1, y1, x2, y2; /* coordinates of 2 points */
double distance;
double diff_x, diff_y; /*temporary values used in calculations */

printf("Enter coordinates of the first point x1, y1\n");


printf("and the second point x2, y2\n:");
if(scanf("%f %f %f %f", &x1, &y1, &x2, &y2) != 4)
{
printf("Invalid input. The program is terminated.");
/* argument "1" in the exit() function indicates
an abnormal program termination */
exit(1);
}
else
{
diff_x = (x2 - x1)*(x2 - x1);
diff_y = (y2 - y1)*(y2 - y1):

distance = sqrt(diff_x + diff_y);

printf("The distance between two points with");


printf(" coordinates (%.3f,%.3f) and (%.3f,%.3f) is %.3f",
x1, y1, x2, y2, distance);
}
system("PAUSE");
return 0;
}

Pseudo Random-Number Generator

The int rand(void) function generates and returns an integer in the range [0,
RAND_MAX] each time it is called. Repeated calls generate a randomly distributed
sequence. The rand() function and the constant RAND_MAX = 32767 (which is the
maximum value of the 16-bit integer) are defined in the header file stdlib.h. Although the
sequence generated by the function rand() appears random, it will repeat itself each time
you run the program. To generate an actual random sequence use the following
statement:

srand(time(NULL));

The time(NULL) function requires the header file time.h. It returns the current calendar
time as a number of seconds that have elapsed since 1 January 1970. srand() function is
used to pass to the rand() function different seeds (initial values) each time it is called.
The seed is given by the return value of the time(NULL).

To generate a random number in the range other than [0, RAND_MAX], the remainder
operator can be used. For example, the following call will return a random number in the
range [0, 99]:

rand()%100;

To include negative numbers you can subtract half of the range from the result for each
number generated:

rand()%100 - 50;

The range in the latter case is [-50, 49].

You can also generate floating-point numbers, as in the following code fragment.

float x, y;
int random_number1, random_number2;
int n1, n2

srand(time(NULL));

/*generates an integer in the range [-100, 99] */


random_number1 = rand()%200 - 100;

/*generates an integer in the range [20, 79] */


random_number2 = rand()%60 + 20;

/*creates a floating-point random number


in the range [-10.0, 9.9] using the number generated above*/
x = random_number1/10.0;

/*another floating-point random number in the range [1.000 – 99.999]


with 3 digits after the decimal point */

n1 = rand()%100 + 1; /*’whole’ part of the number in


the range [1, 100] */
n2 = rand()%1000; /*3 digits integer for the decimal part */

y = n1 + n2/1000.0; /*required floating-point number*/

Summary:

• In C language a stream is a series of bytes.


• A stream is a variable of the type FILE.
• The standard input stream for reading is stdin which is usually the keyboard.
• The standard output stream for writing is stdout, which is usually the screen.
• To use the standard I/O functions the program must include the header file
stdio.h.
• The format specifiers are used within the printf() function to format the output.
• You can set the minimum width, alignment and number of decimal places in the
output by adding
numbers and dot between the sign % and the letter within the format specifier.
• C library functions putc() and putchar() can be used to write one
character to the standard output.
• C library functions getc() and getchar() can be used to read one
character from the standard input.
• The scanf() function requires format specifiers and addresses of variables to be
passed to it.
• The address operator & returns the address of a variable (location in the computer
memory).
• The scanf() function returns the number of items read, or the EOF constant if an
error occurs.
• The header file math.h contains the function prototypes of the mathematical
functions.
• The rand rand()) is used to generate a pseudo-random sequence in the range
[0, RAND_MAX].

Vous aimerez peut-être aussi