Download Chapter 2 Introduction to the C Language

Transcript
2 Chapter C5802 36410 Page 54 Tuesday, March 28, 2006 1:51 PM
54
Section 2.7 Input/Output
In this chapter, we assume that the source of data is the keyboard and
the destination of data is the monitor. In other words, the terminal devices we
use produce or consume text streams. In C, the keyboard is known as standard input and the monitor is known as standard output.
A terminal keyboard and monitor can be associated only with a text stream.
A keyboard is a source for a text stream; a monitor is a destination for a text
stream.
Figure 2-15 shows the concept of streams and the two physical devices associated with input and output text streams.
Data Source
Program
Input Text Stream
Data
Output Text Stream
Data
keyboard
monitor
Data Destination
FIGURE 2-15 Stream Physical Devices
Formatting Input/Output
The previous section discussed the terminal as a text stream source and destination. We can only receive text streams from a terminal (keyboard) and send
text streams to a terminal (monitor). However, these text streams often represent different data types, such as integer, real, and Boolean. The C language
provides two formatting functions: printf for output formatting and scanf for
input formatting. The printf function converts data stored in the program
into a text stream for output to the monitor; the scanf function converts the
text stream coming from the keyboard to data values and stores them in program variables. In other words, the printf and scanf functions are data to text
stream and text stream to data converters.
Output Formatting: printf
The output formatting function is printf. The printf function takes a set of
data values, converts them to a text stream using formatting instructions contained in a format control string, and sends the resulting text stream to the
standard output (monitor). For example, an integer 234 stored in the program
is converted to a text stream of three numeric ASCII characters (‘2’, ‘3’, and ‘4’)
Copyright © 2007 by Thomson Course Technology. All rights reserved. This publication is protected by federal copyright law. No part of this
publication may be reproduced without prior permission in writing from Course Technology. Some of the product names and company names
have been used for identification purposes only and may be trademarks or registered trademarks of their respective manufactures and sellers.