streaming i/o
DESCRIPTION
Streaming I/O. Handling the input and output of your program. What you know. To read in from a console: cin To output to a console: cout Example: cout > number;. How this happens. Data streams are like queues (more in 241) Reading from data streams - PowerPoint PPT PresentationTRANSCRIPT
Streaming I/OHandling the input and output of
your program
2
What you knowO To read in from a console: cinO To output to a console: cout
O Example:O cout << “Enter a number: “;O cin >> number;
3
How this happensO Data streams are like queues (more
in 241)O Reading from data streams
O console adds to the back of streamO cin reads from the front of stream
O Writing to data streamsO cout adds to the back of the streamO console reads from the front of the
stream
4
Reading From StreamsStream
1 2 3 4
cin
5
Writing to streamsStream
1 2 3 4
cout
6
What makes this possible
O iostream (the power of inheritance)O istream – reads file from streamO ostream – writes file to stream
O Limitation:O Only works with console I/O
7
Using files for I/OO #include <fstream>
O fstream header defines three types to support file I/OO ifstream – reads from a fileO ofstrem – writes to a fileO fstream – read and write to same file
8
Accessing the filesO Create the stream
O ifstream infile; //unbound input file stream
O ofstream outfile; //unbound output file stream
O Bind to a fileO infile.open(“listOfSponsors.txt”);O outfile.open(“listOfAds.txt”);
9
First things first…O The absolute first thing to do is check to
make sure the file opens.O Flags get set when something goes wrong
O badbit – indicates system level failureO failbit – reading wrong type of dataO eofbit – set when eof is reached
O How to check?O if(strm.good()){O //its ok to read from the file
}
10
Learning to readO General syntax: streamName >> variableO Reads until whitespace
O Example: Reading One ValueO infile >> myChar;
O Example: Reading until end of fileO while(infile.good()){
O infile >> sponserName;O sponserVector.push_back(sponserName);
O }
11
Learning to writeO General syntax: streamName <<
variable;
O Examples:O outfile << myInt << endl;O outfile << someString << endl;O outfile << firstRadioAd << endl;
12
Last but not leastO Always remember to close your
streamO General syntax: strm.close();
O Example:O infile.close();O outfile.close();
O Allows for the stream to be bound again
13
Put it all togetherO #include fstream //allows file i/oO using namespace std;O void main(){
O ifstream read; //create an instreamO ofstream write; //create an outstreamO read.open(“someFile.txt”); //bind to fileO write.open(“resultFile.txt”); //bind to fileO while(read.good() && write.good()){
O read >> variable;O write << variable << endl;
O }O read.close();O write.close();
O }
14
Questions?