Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ Programming Certificate University of Washington Cliff Green

Similar presentations


Presentation on theme: "C++ Programming Certificate University of Washington Cliff Green"— Presentation transcript:

1 C++ Programming Certificate University of Washington Cliff Green
© Bruce M. Reynolds & Cliff Green, 2002

2 © Bruce M. Reynolds & Cliff Green, 2002
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

3 © Bruce M. Reynolds & Cliff Green, 2002
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

4 © Bruce M. Reynolds & Cliff Green, 2002
Types of streams Streams for: Input: istream, ifstream, istringstream Output: ostream, ofstream, ostringstream © Bruce M. Reynolds & Cliff Green, 2002

5 © Bruce M. Reynolds & Cliff Green, 2002
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

6 © Bruce M. Reynolds & Cliff Green, 2002
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

7 © Bruce M. Reynolds & Cliff Green, 2002
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

8 © Bruce M. Reynolds & Cliff Green, 2002
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

9 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); // get a character outfile.close(); // close the stream outfile.eof(); // end of stream? cout.precision(); // get the current precision © Bruce M. Reynolds & Cliff Green, 2002

10 © Bruce M. Reynolds & Cliff Green, 2002
Formatting precision() // sets the number of decimal places hex // change the base to hex dec // change the base to dec oct // change the base 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

11 © Bruce M. Reynolds & Cliff Green, 2002
Formatting left, right justification fixed, scientific format of floats width, precision format of numbers fill sets/gets fill character endl adds a CR and flushes flush writes out the buffer ws eats white space plus lots, lots more... © Bruce M. Reynolds & Cliff Green, 2002

12 © Bruce M. Reynolds & Cliff Green, 2002
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

13 © Bruce M. Reynolds & Cliff Green, 2002
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

14 Streams are sophisticated objects!
ios istream ostream ifstream iostream ofstream fstream © Bruce M. Reynolds & Cliff Green, 2002

15 © Bruce M. Reynolds & Cliff Green, 2002
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

16 © Bruce M. Reynolds & Cliff Green, 2002
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

17 © Bruce M. Reynolds & Cliff Green, 2002
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

18 © Bruce M. Reynolds & Cliff Green, 2002
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

19 © Bruce M. Reynolds & Cliff Green, 2002
In-core formatting istringtream for input stream processing #include <sstream> // old hdr is strstream #include <string> using std::istringstream; using std::string; istringstream s(“ This is a test”); int i; float f; string buff; s >> f >> i >> buff; // buff == “This” © Bruce M. Reynolds & Cliff Green, 2002

20 © Bruce M. Reynolds & Cliff Green, 2002
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

21 © Bruce M. Reynolds & Cliff Green, 2002
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

22 © Bruce M. Reynolds & Cliff Green, 2002
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

23 © Bruce M. Reynolds & Cliff Green, 2002
istream functions get( char ) gets one character returns istream returns EOF on end-of-file get() gets one character returns the character 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

24 © Bruce M. Reynolds & Cliff Green, 2002
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

25 © Bruce M. Reynolds & Cliff Green, 2002
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

26 © Bruce M. Reynolds & Cliff Green, 2002
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

27 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

28 Other useful manipulators
tie synchronizes input and output to ensure that outputs occur before subsequent inputs © Bruce M. Reynolds & Cliff Green, 2002

29 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

30 << 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

31 << 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

32 © Bruce M. Reynolds & Cliff Green, 2002
<< 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

33 << 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


Download ppt "C++ Programming Certificate University of Washington Cliff Green"

Similar presentations


Ads by Google