400 likes | 577 Views
CIS 4930 Application Development Using C++ Dr. Kun Suk Kim CISE Department, University of Florida. Input/Output Using Stream Classes. Notice. Web site http://www.cise.ufl.edu/~cis4930sp04ad/ E-mail TAs to inform your name and cise account Check class home page at least once a week.
E N D
CIS 4930Application Development Using C++Dr. Kun Suk KimCISE Department, University of Florida Input/Output Using Stream Classes
Notice • Web site • http://www.cise.ufl.edu/~cis4930sp04ad/ • E-mail TAs to inform your name and cise account • Check class home page at least once a week
Character I/O with Files • All cin and cout character I/O same forfiles! • Member functions work same: • For input: get, getline, putback, peek, ignore • For output: put, flush
Checking End of File • Use loop to process file until end • Typical approach • Two ways to test for end of file • Member function eof()inStream.get(next);while (!inStream.eof()) { cout << next; inStream.get(next);} • Reads each character until file ends • eof() member function returns bool
End of File Check with Read • Second method • read operation returns bool value!(inStream >> next) • Expression returns true if read successful • Returns false if attempt to read beyond end of file (if the failbit or badbit is set) • In action:double next, sum = 0;while (inStream >> next) sum = sum + next;cout << “the sum is “ << sum << endl;
Stream State and Boolean Conditions • operator void * () • Returns whether the stream has not run into an error • Corresponds to !fail() • while (inStream >> next) { … } • operator ! () • Return whether the stream has run into an error • Corresponds to fail() • if (! (std::cin >> x)) { … } • std::cin >> x;if (std::cin.fail()) { … }
Formatting Output • Formatting numeric values for output • Values may not display as you’d expect!cout << “The price is $” << price << endl; • If price (declared double) has value 78.5, youmight get: • The price is $78.500000 or: • The price is $78.5 • We must explicitly tell C++ how to outputnumbers in our programs!
Formatting Numbers • ‘Magic Formula’ to force decimal sizes:cout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precision(2); • These stmts force all future cout’ed values: • To have exactly two digits after the decimal place • Example:cout << “The price is $” << price << endl; • Now results in the following:The price is $78.50 • Can modify precision ‘as you go’ as well!
Formatting Output with Stream Functions • Can use on any output stream • File streams have same member functionsas cout object
Output Member Functions • Consider: outStream.setf(ios::fixed); outStream.setf(ios::showpoint); outStream.precision(2); • Member function precision(x) • Decimals written with ‘x’ digits after decimal • Member function setf() • Allows multitude of output flags to be set
More Output Member Functions • Consider: outStream.width(5); • Member function width(x) • Sets width to ‘x’ for outputted value • Only affects ‘next’ value outputted • Must set width before each value in order toaffect all • Typical to have ‘varying’ widths • To form ‘columns’
Flags • Recall: member function setf() • Sets condition of output flags • All output streams have setf() member • Flags are constants in class ios • In library <iostream>, std namespace
setf() Examples • Common flag constants: • outStream.setf(ios::fixed); • Floating-point numbers are written in fixed-point notation (decimal) • outStream.setf(ios::scientific); • Floating-point numbers are written in e-notation • outStream.setf(ios::showpoint) • Always include decimal point • outStream.setf(ios::showpos) • A plus sign is output before positive integer values
setf() Examples • Common flag constants: • outStream.setf(ios::right); • Sets right-justification • outStream.setf(ios::left); • outStream.setf(ios::dec) • Integers are output in decimal (base 10) notation • outStream.setf(ios::oct); • outStream.setf(ios::hex);
setf() Examples • Common flag constants: • outStream.setf(ios::uppercase); • An uppercase E is used in scientific notation • outStream.setf(ios::showcase); • Show the base of an output number • Leading 0 for octal • Leading 0x for hexadecimal • Set multiple flags with one call:outStream.setf(ios::fixed | ios::showpoint | ios::right);
Manipulators • Manipulator defined:“A function called in nontraditional way” • Can have arguments • Placed after insertion operator • Do same things as member functions! • In different way • Common to use both ‘together’
Manipulators • flush and endl defined in <ostream> • setw() and setprecision() are in library<iomanip>, std namespace
How Manipulators Work • By function overloading • Manipulators are functions that are passed to I/O operators as arguments • The functions are then called by the operator • Example: • std::cout << std::endl
How Manipulators Work ostream& ostream::operator << (ostream& (*op) (ostram&)) { // call the function passed as parameter with // this stream as the argument return (*op) (*this); } std::ostram& std::endl (std::ostream& strm) { strm.put(‘\n’); // write newline strm.flush(); // flush the output buffer return strm; // return strm to allow chaining }
How Manipulators Work • Use this manipulator in an expression • std::cout << std::endl • Implementation of operator << transforms this call Into a call of the passed function with the stream as the argument • std:endl(std::cout)
User-Defined Manipulators • An example of user-defined manipulator • Ignores all characters until end-of-line #include <istream> #include <limits> template <class charT, class traits> Inline std::basic_istream<charT,traits>& ignoreLine (std::basic_istream<charT,traits>& strm) { // skip until end-of-line strm.ignore(std::numeric_limits<int>::max(), strm.widen('\n')); // return stream for concatenation return strm; }
User-Defined Manipulators #include <iostream> #include "ignore.hpp“ using namespace std; int main() { int i; cout << "read int and ignore one line" << endl; cin >> i; cin >> ignoreLine; cout << "int: " << i << endl; cout << "read int and ignore two lines" << endl; cin >> i; cin >> ignoreLine >> ignoreLine; cout << "int: " << i << endl; } read int and ignore one line 1 first line int: 1 read int and ignore two lines 2 first line second line int: 2
Manipulator Example: setw() • setw() manipulator:cout << “Start” << setw(4) << 10 << setw(4) << 20 << setw(6) << 30; • Results in:Start 10 20 30 • Note: setw() affects only NEXToutputted value • Must include setw() manipulator before eachoutputted item to affect all
Manipulator setprecision() • setprecision() manipulator:cout.setf(ios::fixed | ios::showpoint); cout << “$” << setprecision(2) << 10.3 << “ “ << “$” << 20.5 << endl; • Results in:$10.30 $20.50
Formatting Tools for Class ostream • Output stream member functions • Description • Corresponding manipulator • setf(ios_flag) • Set flags • setioflags(ios_flag) • unsetf(ios_flag) • Unset flags • resetioflags(ios_flag) • setf(0, ios::floatfield) • Restores default flag settings • None
Formatting Tools for Class ostream • precision(int) • Sets precision for floating-point number ouput • setprecision(int) • precision() • Returns the current precision setting • None • width(int) • Sets the output field width; applies only to the next item output • setw(int) • fill(char) • Specifies the fill character when the output field is larger than the value output; the default is a blank • setfill(char)
Saving Flag Settings • Flag settings ‘stay’ until changed • Precision and setf flags can be savedand restored • Function precision() returns current settingif called with no arguments • Member function flags() provides similarcapability
Saving Flag Settings Example • void outputStuff(ofstream& outStream) { int precisionSetting = outStream.precision(); long flagSettings = outStream.flags(); outStream.setf(ios::fixed | ios::showpoint); outStream.precision(2);Do whatever you want here. outStream.precision(precisionSetting); outStream.flags(flagSettings);} • Function to save & restore ‘typical’ settings • Call: outputStuff(myStream);
Restoring Default setf Settings • Can also restore default settings: cout.setf(0, ios::floatfield); • Not necessarily the ‘last’ setting! • Default values are implementation-dependent • Does not reset precision settings • Only setf settings
Stream Hierarchies • Class Relationships • ‘Derived from” • One class obtained from another class • Then features are ‘added’ • Example: • Input file streams class is derived from classof all input streams • It then adds open and close member functions • i.e.: ifstream is derived from istream
ios_base ios_base<> ios / wios basic_istream<> istream / wistream basic_ostream<> ostream / wostream basic_iostream<> iostream / wiostream Hierarchy of Stream Classes
Class Inheritance ‘Real’ Example • Class of all convertibles is derived fromclass of all automobiles • Every convertible is an automobile • Convertible ‘adds features’ to automobile
Stream Class Inheritance • Consider: • If D is derived class of class B • All objects of type D are also of type B • e.g.: A convertible is also an automobile • Regarding streams: • An ifstream object is also an istreamobject • Should use istream objects for parameters • More objects can be plugged in!
Stream Class Inheritance Example Calls • Considering previous functions: • twoSumVersion1(fileIn); // Legal! • twoSumVersion1(cin); // ILLEGAL! • Because cin is not of type ifstream! • twoSumVersion2(fileIn); // Legal! • twoSumVersion2(cin); // Legal! • More versatile • istream parameter accepts both objects
Random Access to Files • Sequential Access • Most commonly used • Random Access • Rapid access to records • Perhaps very large database • Access ‘randomly’ to any part of file • Use fstream objects • input and output
Random Access Tools • Opens same as istream or ostream • Adds second argument • fstream rwStream;rwStream.open(“stuff”, ios::in | ios:: out); • Opens with read and write capability • Move about in file • rwStream.seekp(1000); • Positions put-pointer at 1000th byte • rwStream.seekg(1000); • Positions get-pointer at 1000th byte
Random Access Sizes • To move about must know sizes • sizeof() operator determines number of bytesrequired for an object:sizeof(s) //Where s is string s = “Hello”sizeof(10) // 4sizeof(double) // 8sizeof(myObject) • Position put-pointer at 100th record of objects:rwStream.seekp(100*sizeof(myObject) – 1);
Summary 1 • Streams connect to files with openoperation • Member function fail() checks successes • Stream member functions format output • e.g.: width, setf, precision • Same usage for cout (screen) or files • Stream types can be formal parameters • But must be call-by-reference
Summary 2 • istream (no ‘f’) parameters accept cinor ifstream objects as arguments • ostream (no ‘f) parameters accept coutor ofstream objects as arguments • Member function eof • Used to test for end of input file