CS Week 2 - Streams Flashcards
ostream
output stream
a class that supports output
available via iostream and in namespace std
insertion operator
«_space;
for converting different types of data into a sequence of characters, that sequence is normally placed into a buffer, and the system then outputs the buffer at various times
cout
a predefined ostream object that is pre-associated with a system’s standard output, usually a computer screen
how the ostream «_space;works
- the insertion operator converts the string literal to characters, temporarily storing characters in an output buffer
- the system then writes the buffer’s content to the screen
istream
input stream
a class that supports input
available via iostream
extraction operator
> > to extract data from a buffer and write the data into different types of variables
cin
a predefined istream pre-associated with a system’s standard input, usually a keyboard
how istream»_space; works
- the system automatically puts the standard input into a data buffer associated with cin
- > > operator skips leading whitespace and extacts as many characters as possible consistent with the target variable’s type
- the operator then stops at the next whitespace
- converts the extracted characters to the target variable’s type and stores the result into the variable
to read file input
include <fstream></fstream>
can create a new input stream that comes from a file
ifstream inFS;
inFS.open(str);
if(!inFS.is_open()){
cout «_space;“error opening”; return 1;}
inFS»_space; aVar;
inFS.close();
when would we use cin, cout, ifstream, ofstream, istringstream, ostringstream
cin - input from the keyboard
cout - output to the screen
ifstream - input from a file
ofstream - write to a file
istringstream - read input from a string
ostringstream - insert characters into a string buffer (instead of screen)
reading to the end of the file
while (inFS»_space; aVar) {
//do something with aVar;
}
inFS.eof();
returns true if the previous stream operation reached the end of the file
inFS.fail();
returns true if the previous stream operation had an error
- instead of this use while (inFS»_space; aVar){ /do something/ }
stream error
occurs when insertion or extraction fails causing the stream to enter an error state
- wrong type, too large, too small
- may skips extraction, set the var to 0, or set the var to the max or min of the type
inFS.clear();
inFS.good();
inFS.eof();
inFS.fail();
inFS.bad();
and when to use
1-bit error flags
clear - stream’s error state is cleared
good- returns true if no stream errors have occurred
eof - returns value of eofbit, if end of file reached on extraction
fail - returns true if either failbit or badbit is set, indicating an error for the previous stream operation
bad - returns true id badbit is set. indicating the stream is bad
- use if you want to know what went wrong