180 likes | 295 Views
Data Streams. Extraction. 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.
E N D
Extraction • 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
Extraction • Questions
Extraction • 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?
Extraction • How do we extract whitespace? • Unformatted Extraction • Character Extraction • The get function – extracts a single character from the stream. • String Extraction • The getlinefunction – extracts a string from the stream. • It needs a delimiter (or just use the default)
Extraction • 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.
Extraction • 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 • 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 Monitor Program.exe cin cout Stream Diagram 1.0
Streams • Questions
Streams • 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 Program.exe cin cout File.in File.out Stream Diagram 2.0
Keyboard Monitor Program.exe cin cout File.in File.out Stream Diagram 2.0
File Streams • Include the header file for file streams • #include <fstream> • Declaration of a input file stream • ifstream fin; // you can use any variable name • Declaration of a output file stream • ofstreamfout; // you can use any variable name • Is that it? Can we use these file streams now?
File Streams • 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 Program.exe cin cout File.in File.out fout fin Stream Diagram 2.0
File Streams • Questions
File Streams • Questions • How do we use these streams now?