Plugin-00 - C++ IO Background
Plugin-00 - C++ IO Background
Background Material
Input/Output Input/Output
Streams Streams
A popular model for how input and output is done in computer In general, there are two kinds of stream data: characters and
systems is centered around the notion of a stream. binary data.
A stream is just a sequence of data with functions to put data into
one end, and take them out of the other.
Characters are usually used for:
For example: Communicating between your program and a keyboard and/or screen.
keyboard program Reading and writing files, such as when you are editing a text file.
display program
file program
In addition to text, files can contain arbitrary binary data.
In C++, streams are unidirectional. It is usually much more efficient to pass binary representations of
Data is always passed through the stream in one direction. things than equivalent character representations.
If you want to read and write data to the same file or device, you However, compared to binary data, character streams are easier for
have to use two streams. humans to understand and debug.
Input/Output Input/Output
Streams A brief note on Binary Streams
In general, there are two kinds of stream data: characters and Binary streams are useful for transferring data
Asbinary
computers
data. and networks get faster, and structures into and out of memory with lower overhead.
storage becomes cheaper, the efficiency For example, a 32-bit binary representation of an integer
Characters are usually
argument becomes used for:weaker. So we'll be fits into four bytes, whereas a character representation
Communicating between your program and a keyboard or screen. of the number could take as much as 11 bytes.
talking about character streams here.
Reading and writing files, such as when you are editing a text file. -232
1
9/1/10
Input/Output Input/Output
Alternate Output Streams Output Streams
You can also use the shell’s redirection facility to move the The insertion operator inserts strings and character variables
output end of the screen’s stream to a file: directly into the stream.
% ./hello > foo It knows how to convert all of the other standard data types
This connects the output end of the cout stream to the file to characters before inserting them into the stream.
“foo”.
There is another output stream object defined by the For example:
iostream library called cerr. int foo = 42;
This stream is identical in most respects to the cout cout << foo << endl;
stream; in particular, its output defaults to the screen as well. outputs the string “42\n” to the screen (the “\n” represents
By convention, programs use the cerr stream for error newline). The manipulator endl inserts a single newline.
messages and the like.
2
9/1/10
Input/Output Input/Output
Output Streams Buffering
The insertion operator may be cascaded: I/O in C++ is buffered.
int foo = 47;
This means output inserted into an output stream is saved by
int bar = 11;
cout << foo << bar << endl; the underlying operating system (in a region of memory
and this outputs “4711\n”. called a buffer).
It is only allowed to escape out of the output end of the
If you want nicer spacing, you have to do it yourself, either by: stream if:
cout << foo << " " << bar << endl; a newline is inserted into the stream,
// or
the buffer becomes full,
cout << foo << setw(3) << bar << endl;
the program decides to read from cin, or
Here the setw() manipulator sets the width of the following the program exits.
number to three positions and right-justifies the number within
that field.
Input/Output Input/Output
Buffering Input Streams
As a consequence of buffering, you won't see any output until Now, let's next take a look at stream input. Consider the
the newline arrives, and then you'll get the whole line at statement:
once.
cin >> foo;
Usually you won't notice this, but sometimes you do…
C++ defines the object cin as the stream associated with
the standard input device currently connected to the
Question: When would you notice this?
program. So, this stream is an input stream.
Answer: If you forget the newline and your program doesn't
immediately output/input something else. By default, this device is the keyboard; thus, characters typed
Exercise: Can you think of a situation where this in by you appear come to your program through the cin
might be a problem? stream.
“Debugging” using cout statements The >> is called the extraction operator, and is used to
As a consequence of this, output sent to cerr is not extract things from the input stream.
buffered.
3
9/1/10
Input/Output Input/Output
Input Streams Input Streams
Finally, the get() function reads a single character, whitespace or no:
Strings too are delimited by whitespace.
char ch;
If you need to read strings including whitespace, use the cin.get(ch);
getline() function here: So, we can accomplish what we'd hoped to by:
cin >> foo >> bar; cin >> foo >> bar;
getline(cin, baz); for (int i=0; i<3; i++) {
cin.get(ch);
}
getline() reads all characters up to but not including getline(cin, baz);
the next newline and puts them into the string variable. It
then discards the newline. 42 3.14 four score\n
Thus the above reads “ four score” into baz; it This makes foo 42, bar 3.14, and baz “four score”.
keeps the leading three spaces, but throws away the “\n”. Don't be bothered that the three methods have such different syntax.
The three methods can be freely intermixed.
Input/Output Input/Output
Input Streams Input Streams
Question: Can get(), or getline() for that Like cout, cin is buffered.
matter, get you into trouble?
Answer: Yes Characters typed in response to a prompt from the program
If a call to cin.get(ch) follows the use of the (which uses cin to gather input) are stored in a buffer until
extraction operator, get() will get the first the enter key is pressed.
whitespace character that stopped the extraction.
This is often the “\n” ending the line, instead of the The characters are then made available to the program in one
first character of the next input line, which is large group.
probably what the programmer intended.
This also allows for greater efficiency, and it lets you correct
errors before your program sees them (i.e. you can go back
and fix something you typed wrong).
Input/Output Input/Output
A note about buffered input Alternate Input Streams
Buffered input can confuse you, because your program You can use the shell’s redirection facility to move the input
will not demand more input from the keyboard until it end of the stream from the keyboard to a file:
has used up a non-empty buffer.
Consider the program fragment:
% prog < foo
int foo, bar;
cin >> foo; // statement 1 When doing this, remember that the input will not appear on
// some computation your screen since you did not enter it on the keyboard; this
cin >> bar; // statement 2 makes for funny-looking output, as the input is not echoed.
If you type “4 2\n” and newline in response to Try this with your project 1 code and you will see what I mean.
statement 1, the value 4 will be assigned to foo. The
remaining characters “ 2\n” (including the space before
the 2) remain in the input buffer until the next attempt
is made to extract from cin, at statement 2.
4
9/1/10
Input/Output
Failed Input Streams
Even if you clear a failed stream, the offending characters
are left in the stream and must be consumed before more
data can be read from it.
C++ provides one way to consume such characters:
cin.ignore(200, '\n');
This reads characters from cin, stopping after it reads 200
characters or a “\n”, whichever comes first.
Nothing is special about the 200, but you have to write some
value, or it will stop after one character.
5