Week 5 lecture notes, C++ Streams

advertisement
C++ Streams
C++ Programming Certificate
University of Washington
Cliff Green
© Bruce M. Reynolds & Cliff Green,
2002
1
C++ Streams
Input and Output
• C++ uses streams for input and output
• Like C, these are not defined within the language, but in
the library
• What is a stream?
– Think of a stream as a sequence of characters
• To use streams, we must add “#include <iostream>”
• All standard library components are in the std
namespace, so appropriate directives or qualifications
must be used
– using std::cout;
© Bruce M. Reynolds & Cliff Green,
2002
2
C++ Streams
Why use streams?
• printf potentially wastes run-time memory
– entire printf library is loaded to output a single char
• printf is theoretically slower than C++ streams
– the format string is parsed at run-time instead of
compile-time
– the C library does benefit from more years of
performance tuning, however
• printf allows no compile-time type checking
– no protection against arguments not matching the
format specifier
• printf is hard to extend to new types
– %c, %d, %s, %f
© Bruce M. Reynolds & Cliff Green,
2002
3
C++ Streams
Types of streams
• Streams for:
– Input:
istream, ifstream, istringstream
– Output: ostream, ofstream, ostringstream
© Bruce M. Reynolds & Cliff Green,
2002
4
C++ Streams
Stream operators
• ostream
– output is called “insertion”
– << is the “insertion” operator
– Value is inserted into the output stream
• istream
– input is called “extraction”
– >> is the “extraction” operator
– Value is extracted from the input stream
© Bruce M. Reynolds & Cliff Green,
2002
5
C++ Streams
Well-known streams
• Global stream objects are defined in <iostream>
– cin
istream object connected to standard input
– cout
ostream object connected to standard output
– cerr
ostream object connected to standard error
– clog
ostream object connected to standard error
providing buffered output
© Bruce M. Reynolds & Cliff Green,
2002
6
C++ Streams
Examples
#include <iostream>
using std::cout; using std::cin; using std::endl;
cout << “Hello, World” << endl;
// endl is equivalent to “\n”, plus a buffer flush
int nValue = 123;
cout << “Value is” << nValue << endl;
cin >> nValue;
cout << “The new value is” << nValue << endl;
© Bruce M. Reynolds & Cliff Green,
2002
7
C++ Streams
Type-safety
• Streams can accept
– Any built-in data type
– Any complex expression that evaluates to a built-in
data type
– Any type that can be implicitly converted to a built-in
data type
– Any user-defined type for which the << or >>
operators have been defined
© Bruce M. Reynolds & Cliff Green,
2002
8
C++ Streams
C++ classes preview (or review)
• Streams are instances of C++ classes.
• Class instances (generally called objects) are like
structures in that they have fields (generally called
members).
• Members can be data or functions (methods).
• We use the “.” syntax to access members
infile.get(ch);
outfile.close();
outfile.eof();
cout.precision();
© Bruce M. Reynolds & Cliff Green,
2002
//
//
//
//
get a character
close the stream
end of stream?
get the current precision
9
C++ Streams
Formatting
•
•
•
•
precision()
hex
dec
oct
//
//
//
//
sets the number
change the base
change the base
change the base
of decimal places
to hex
to dec
to oct
#include <iomanip>
using std::cout; using std::endl;
cout.precision( 4 )
cout << std::hex << 100 << endl; // prints “64”
cout << std::dec << 100 << endl; // prints “100”
cout << std::oct << 100 << endl; // prints “144”
© Bruce M. Reynolds & Cliff Green,
2002
10
C++ Streams
Formatting
•
•
•
•
•
•
•
left, right
fixed, scientific
width, precision
fill
endl
flush
ws
justification
format of floats
format of numbers
sets/gets fill character
adds a CR and flushes
writes out the buffer
eats white space
• plus lots, lots more...
© Bruce M. Reynolds & Cliff Green,
2002
11
C++ Streams
Output
put( char c )
Output a single character
cout.put( ‘a’ );
// prints “a”
write ( char const * s, int n )
Output n characters from string s
char const * str = “My name is”;
cout.write( str, 6 );
// prints “my nam”
© Bruce M. Reynolds & Cliff Green,
2002
12
C++ Streams
Input
get ( char c ) // inputs a single character
char c;
cin.get( c );
// reads one character
getline ( char * s, int n )
Input up to n characters from standard input until “\n”
getline ( istream&, string& )
Inputs characters from istream until “\n” (safer and more
convenient than getline into a character array)
getline (cin, str);
© Bruce M. Reynolds & Cliff Green,
2002
13
C++ Streams
Streams are sophisticated objects!
ios
istream
ifstream
ostream
iostream
ofstream
fstream
© Bruce M. Reynolds & Cliff Green,
2002
14
C++ Streams
Stream error states
• cin.eof()
– true if end-of-file has been encountered
• cin.fail()
– true when a format error has occurred
– characters have not been lost
– it is normally possible to recover from such a failure
• cin.bad()
– true when an error occurs that results in loss of data
– serious failures are normally not recoverable
• cin.good()
– true if bad(), fail() and eof() are all false
© Bruce M. Reynolds & Cliff Green,
2002
15
C++ Streams
File processing
• Must include <iostream>
• Must also include <fstream>
• File open and creation modes
• ios::app
append only
• ios::ate
open and seek to the end
• ios::in
input
• ios::out
output
• ios::trunc
if file exists, overwrite it
• ios::binary
open file in binary mode
© Bruce M. Reynolds & Cliff Green,
2002
16
C++ Streams
File processing
• Output file stream example
– ofstream outFile( “filename”, ios::trunc );
• Input file stream example
– ifstream inFile( “filename”, ios::in );
© Bruce M. Reynolds & Cliff Green,
2002
17
C++ Streams
File processing
ios overloaded operator member functions
•
operator!
– returns true if fail() or bad() would return true
– example:
if ( !outFile ) ...
• operator void*
– converts the stream to a pointer which is NULL if fail()
or bad() would return true
– example:
while ( inFile >> name ) ...
© Bruce M. Reynolds & Cliff Green,
2002
18
C++ Streams
In-core formatting
• istringtream for input stream processing
#include <sstream> // old hdr is strstream
#include <string>
using std::istringstream; using std::string;
istringstream s(“1.414 47 This is a test”);
int i; float f;
string buff;
s >> f >> i >> buff; // buff == “This”
© Bruce M. Reynolds & Cliff Green,
2002
19
C++ Streams
In-core formatting
•
•
ostringstream for output stream processing
the str() method of ostringstream returns a string object
#include <sstream>
#include <string>
using std::ostringstream; using std::string;
int i(20), j(30);
ostringstream os;
os << “i = “ << i << “, j = “ << j;
string s (os.str());
© Bruce M. Reynolds & Cliff Green,
2002
20
C++ Streams
Manipulators
• Manipulators perform formatting tasks
• Requires the inclusion of <iomanip>
• Can take zero or one argument
• Examples
– setw
– setprecision
– dec, oct, hex, setbase
© Bruce M. Reynolds & Cliff Green,
2002
21
C++ Streams
Manipulators
• Manipulators are functions
• Manipulators may be user-defined
– ostream& bell( ostream& os ) { return os << ‘\a’; }
– ostream& tab( ostream& os ) { return os << ‘\t’; }
© Bruce M. Reynolds & Cliff Green,
2002
22
C++ Streams
istream functions
• get( char ) gets one character
– returns istream
– returns EOF on end-of-file
• get() gets one character
– returns the character
– returns EOF on end-of-file
• get( char* buff, int limit, char delimiter)
– terminates when the delimiter is read
– reads up to limit-1 characters
– does not read the delimiter
© Bruce M. Reynolds & Cliff Green,
2002
23
C++ Streams
istream functions
• getline()
– operates like the three-argument get using CR
– does not store the delimiter
– alternate version is non-member fct, takes istream as
first arg, string as second, delimiter as third
• ignore skips the specified number of characters
• putback places the previous character obtained by get
back on the stream
• peek returns the next character, but does not remove it
from the stream
© Bruce M. Reynolds & Cliff Green,
2002
24
C++ Streams
istream functions
• failbit is set if the fewer than the specified number of
characters is read
• gcount returns the number of characters input by the
previous read
© Bruce M. Reynolds & Cliff Green,
2002
25
C++ Streams
istream functions
• operator>>( char *)
• operator>>( string )
– inputs the next word (delimited by white space)
– automatically skips white space
– setw sets the maximum string size
© Bruce M. Reynolds & Cliff Green,
2002
26
C++ Streams
Other useful manipulators and functions
• showpoint
– output a floating-point number with a decimal point
– number of significant digits specified by the precision
• uppercase
– forces X or E for hex or floating point
– forces all characters of hex to be uppercase
• boolalpha
– forces boolean values to be output as “true”, “false”
© Bruce M. Reynolds & Cliff Green,
2002
27
C++ Streams
Other useful manipulators
• tie
– synchronizes input and output to ensure that outputs
occur before subsequent inputs
© Bruce M. Reynolds & Cliff Green,
2002
28
C++ Streams
Hints for using iostreams
• Seeking within streams
– ios::begin
– ios::end
– ios::cur
• Don’t forget operator precedence
– Precedence of << is relatively low
– Most expressions are OK without parentheses
• cout << a * b + c << endl;
– Other operators have lower precedence!
• cout << ( a == b ? “equal” : “not equal” );
© Bruce M. Reynolds & Cliff Green,
2002
29
C++ Streams
<< and >> as non-member operators
• The stream insertion operator<< and stream extraction
operator>> are overloaded in compiler libraries to handle
data items of
– built-in types
– strings
– pointer values
• To use these operators with user-defined types, each
class must overload the operators
• Cannot be a member function of the class, since the
stream (not the class object) is the left-hand argument to
the operator.
© Bruce M. Reynolds & Cliff Green,
2002
30
C++ Streams
<< and >> as non-member operators, traditional
technique
class MyClass {
friend ostream &operator<<(
ostream&, MyClass const& );
};
ostream& operator<<( // implementation
ostream &os, MyClass const& rhs) {
...
}
© Bruce M. Reynolds & Cliff Green,
2002
31
C++ Streams
<< and >> as non-member operators, alternative
technique (no friend functions)
class MyClass {
public:
ostream& streamOut (ostream&) const;
};
ostream& operator<<(ostream &os,
MyClass const& rhs) {
return rhs.streamOut(os);
}
ostream& MyClass::streamOut(ostream& os) const {
return os << “ … “;
}
© Bruce M. Reynolds & Cliff Green,
2002
32
C++ Streams
<< and >> as non-member operators
• Serialization: define ostream<< and istream>>
overloading for all your classes.
– Allows the class to write itself to any persistent
storage (file) and recover its contents back from the
file.
• Debugging hint: Define ostream<< for all your classes!
– Allows the developer to see the internal structure of
the object with one line of code.
© Bruce M. Reynolds & Cliff Green,
2002
33
Download