0% found this document useful (0 votes)
58 views

Plugin-00 - C++ IO Background

This document provides background information on input/output streams in C++. It discusses the stream model where input and output is handled through streams that act as sequences to put data into and take data out of. It specifically covers character streams, which are useful for communication with keyboards, screens, and text files. The document also introduces the cout output stream in C++ and how to perform basic output operations like inserting strings and values.

Uploaded by

Matthew Tsang
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Plugin-00 - C++ IO Background

This document provides background information on input/output streams in C++. It discusses the stream model where input and output is handled through streams that act as sequences to put data into and take data out of. It specifically covers character streams, which are useful for communication with keyboards, screens, and text files. The document also introduces the cout output stream in C++ and how to perform basic output operations like inserting strings and values.

Uploaded by

Matthew Tsang
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

9/1/10

C++ I/O - Background


  We assume most of you know how to do I/O in C++. These
notes are for those who would like a refresher course.
C++ I/O

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

  In addition to text, files can contain arbitrary binary data. -2147483648 - 2 1 4 7 4 8 3 6 4 8


  It is usually much more efficient to pass binary representations of 0x 8 0 0 0 Characters
things than equivalent character representations.
Binary
  However, compared to binary data, character streams are easier for
  There are also the added costs of converting from
humans to understand and debug.
characters to binary and back again.

1  
9/1/10  

Input/Output Input/Output cout << "Hello, world!\n";


Streams Streams
  The C++ (not the C) stream I/O model is designed to make   In order to make the stream objects and operators visible,
it easy to input/output values of simple types (like ints and you need the following at the beginning of your file:
doubles) and strings delimited by whitespace. #include <iostream>
  You also get a few controls to adjust things like the field using namespace std;
width of a number to be output, but it's hard to do just about
anything else.
  The #include statement brings in all of the symbols
(functions, variables, etc.) defined in the iostream
  First, let’s look at stream output. Consider the statement: library.
  The using statement tells the compiler you want to use all
cout << "Hello, world!\n"; of the symbols associated with the “standard” namespace.

Input/Output cout << "Hello, world!\n"; Input/Output


Output Streams Output Streams
  C++ defines the object cout as the stream associated with   So if you compile this “hello” program:
the standard output device currently connected to the #include <iostream>
program. So, this stream is an output stream. using namespace std;
void main() {
cout << "Hello, world!\n";
  By default, this device is the screen; thus, characters sent to
}
cout appear on the screen.
and run it:
% ./hello
  The << is called the insertion operator, and is used to insert the output would be:
things into the output stream. Hello, world!
  Here % is the shell prompt, and you type “./hello” and a
newline to invoke the program hello, which sends the string
“Hello, world!” to the screen, followed by a newline.

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.

Input/Output cin >> foo; Input/Output


Input Streams Input Streams
  The extraction operator knows how to convert the characters you   Like the insertion operator, the extraction operator may be
type into values of simple types and strings. cascaded:
int foo;
  In the above example, assuming foo is declared as an integer, if double bar;
you type “42\n”: string baz;
  The extraction operator converts the two characters “4” and “2” into
the binary number 42. cin >> foo >> bar >> baz;
  Stores it in foo.   Input values may be separated by whitespace (which consists of
  These characters are then removed from the input stream. one or more blanks, tabs, or newlines) which is ignored.
  So if you type:
  Question: What's left? 42 3.14 four score\n
  Answer: The “\n” is left in the buffer, to be consumed by the next 42 is assigned to foo, 3.14 to bar, and the string “four” to
use of the extraction operator. baz.

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 Input/Output int foo;


cin >> foo;
Failed Input Streams Failed Input Streams
  The extraction operator will fail if inappropriate data is given   However, if you present it with something that does not
to it. begin with a digit, like:
  For example, if: querty
int foo; then the stream will enter a failed state.
cin >> foo;
is presented with:
  You can test that state of a stream by using it where a bool is
42qwerty\n
expected:
the attempted conversion will succeed, up to the point of the
  It returns true if it is good, false otherwise.
“q”.

  A failed input stream will resist all attempts to extract more


  The stream will be left with “qwerty\n” in it.
data from it, until you clear it via cin.clear().

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.

  Is there another way? Take a minute to figure this out:

do cin.get(ch) while (cin && (ch!='\n'));

5  

You might also like