140 likes | 241 Views
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 << “Enter a number: “; c in >> number;. How this happens. Data streams are like queues (more in 241) Reading from data streams
E N D
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 << “Enter a number: “; • cin >> number;
How this happens • Data streams are like queues (more in 241) • Reading from data streams • console adds to the back of stream • cin reads from the front of stream • Writing to data streams • cout adds to the back of the stream • console reads from the front of the stream
Reading From Streams Stream 1 2 3 4 cin
Writing to streams cout Stream 1 2 3 4
What makes this possible • iostream (the power of inheritance) • istream – reads file from stream • ostream – writes file to stream • Limitation: • Only works with console I/O
Using files for I/O • #include <fstream> • fstream header defines three types to support file I/O • ifstream – reads from a file • ofstrem – writes to a file • fstream – read and write to same file
Accessing the files • Create the stream • ifstreaminfile; //unbound input file stream • ofstreamoutfile; //unbound output file stream • Bind to a file • infile.open(“listOfSponsors.txt”); • outfile.open(“listOfAds.txt”);
First things first… • The absolute first thing to do is check to make sure the file opens. • Flags get set when something goes wrong • badbit – indicates system level failure • failbit– reading wrong type of data • eofbit – set when eof is reached • How to check? • if(strm.good()){ • //its ok to read from the file}
Learning to read • General syntax: streamName >> variable • Reads until whitespace • Example: Reading One Value • infile >> myChar; • Example: Reading until end of file • while(infile.good()){ • infile >> sponserName; • sponserVector.push_back(sponserName); • }
Learning to write • General syntax: streamName<< variable; • Examples: • outfile << myInt << endl; • outfile << someString << endl; • outfile << firstRadioAd << endl;
Last but not least • Always remember to close your stream • General syntax: strm.close(); • Example: • infile.close(); • outfile.close(); • Allows for the stream to be bound again
Put it all together • #include fstream //allows file i/o • using namespace std; • void main(){ • ifstream read; //create an instream • ofstream write; //create an outstream • read.open(“someFile.txt”); //bind to file • write.open(“resultFile.txt”); //bind to file • while(read.good() && write.good()){ • read >> variable; • write << variable << endl; • } • read.close(); • write.close(); • }