Data Streams - Edinboro University of Pennsylvania

Download Report

Transcript Data Streams - Edinboro University of Pennsylvania


Extraction Operator [ cin>> num1]
 Extracts formatted data from an input
stream
 Data in the same format as the data type
that it is being extracted to.
 Ex. extracting to an integer will attempt to
take whatever is in the stream and conform it
to the integer data type.
 Ignores whitespace

Questions

Questions
 How do we extract whitespace?
 What happens if the data in the stream
doesn’t match the data type?
 What if there is junk in the stream and we
need to get rid of it?

How do we extract whitespace?
 Unformatted Extraction
 Character Extraction
 The get function – extracts a single character
from the stream.
 String Extraction
 The getline function – extracts a string from
the stream.
 It needs a delimiter (or just use the default)

What happens if the data in the stream
doesn’t match the data type?
 Stream failure!
 No additional information can be extracted
from the stream
 The status of a stream can be checked using
two functions.
 The good function
 The fail function
 The stream can be reset back to the good
state by using the clear function.

What if there is junk in the stream and
we need to get rid of it?
 We can clear the stream of all the data in the
stream (up to a certain number of characters
or up to a delimiter) by using the ignore
function.

Insertion Operator [ cout << num;]
 Inserts data into an output stream
 We can immediately send all the data in the
stream to the output device using the flush
function.
Keyboard
cin
Monitor
Program.exe
cout
Stream Diagram 1.0

Questions

Questions
 What other devices can we connect to a
program using a stream?
 How do we write to or read from a file?
Keyboard
Monitor
cin
Program.exe
File.in
cout
File.out
Stream Diagram 2.0
Keyboard
Monitor
cin
Program.exe
File.in
cout
File.out
Stream Diagram 2.0

Include the header file for file streams
 #include <fstream>

Declaration of a input file stream
 ifstream fin;

Declaration of a output file stream
 ofstream fout;

// you can use any variable name
// you can use any variable name
Is that it? Can we use these file streams now?

Is that it? Can we use these file streams now?
 No! We need to establish a connection between the file
and the program.

By using the open function we associate a file
stream with a file.
 fin.open ( “file.in” );

Remember to disassociate a stream with a file
after you are done with it.
 fin.close ( );
Keyboard
Monitor
cin
Program.exe
File.in
fin
cout
File.out
Stream Diagram 2.0

Questions

Questions
 How do we use these streams now?