240 likes | 686 Views
C++ Input/Output: Streams. The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams: istream cin built-in input stream variable; by default hooked to keyboard
E N D
C++ Input/Output: Streams The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams: istream cin built-in input stream variable; by default hooked to keyboard ostream cout built-in output stream variable; by default hooked to console header file: <iostream> C++ also supports all the input/output mechanisms that the C language included.
Streams for File I/O • For basic file I/O: #include <fstream> • There are no pre-defined file stream variables, so a programmer who needs to use file streams must declare file stream variables: ifstream inFile; // input file stream object ofstream outFile; // output file stream object • The types ifstream and ofstream are C++ stream classes designed to be connected to input or output files. • File stream objects have all the member functions and manipulators possessed by the standard streams, cin and cout.
Connecting Streams to Files • By default, a file stream is not connected to anything. In order to use a file stream the programmer must establish a connection between it and some file. This can be done by using the open() member function associated with each stream object: inFile.open(“sample.txt"); outFile.open(“sampleout.txt"); • This sets up the file streams to read data from a file called “sample.txt" and write output to a file called “sampleout.txt". • Alternatively: connect stream variable to a file when it is declared: ifstream inFile("readme.data"); ofstream outFile("writeme.data");
Formatting Numeric Output • First of all you need to include the manipulator header file: <iomanip> setw( ): sets the field width (number of spaces in which the value is displayed). setw( ) takes one parameter, which must be an integer. setprecision( ): • sets the precision, the number of digits shown after the decimal point. setprecision( ) also takes one parameter, which must be an integer. The setprecision( ) setting applies to all subsequent floating point values, • In addition, to activate the manipulator setprecision( )for your output stream, insert the following two manipulators once: outStream << fixed << showpoint;
Padding Output • Padding refers to the character used to fill in the unused space in an output field. By default the pad character for justified output is the space (blank) character. • This can be changed by using the setfill() manipulator: int ID = 413225; cout << "0123456789" << endl; cout << setw(10) << ID << endl; cout << setfill('0'); //pad with zeroes cout << setw(10) << ID << endl; cout << setfill(' '); //reset padding to spaces 0123456789 413225 0000413225
Example #include <fstream> #include <iomanip> #include <string> using namespace std; int main() { ofstream oFile("Area.out"); oFile << fixed << showpoint; const double PI = 3.141592654; string figName = "Ellipse"; int majorAxis = 10, minorAxis = 2; double Area = PI * majorAxis * minorAxis; oFile << setw(20) << "Area" << endl; oFile << left << setw(10) << figName; oFile << right << setw(10) << setprecision(4)<< Area << endl; oFile.close(); return 0; }
Further example #include <fstream> // file streams #include <iostream> // standard streams #include <string> // string variable support #include <climits> using namespace std; // using standard library int main() { string EmployeeName, JobTitle; // strings for name and title int EmployeeID; // int for id number ifstream iFile("Employees.data"); // read: getline(iFile, EmployeeName, '\t'); // read to first tab getline(iFile, JobTitle, '\t'); // read to next tab iFile >> EmployeeID; // extract id number iFile.ignore(MAX, '\n'); // skip to start of next line The extraction ends when MAX characters have been extracted and discarded or when the character \n is found
File output while (iFile) { // read to input failure cout << "Next employee: " << endl; // print record header cout << EmployeeName << endl // name on one line << JobTitle // title and id number << EmployeeID << endl << endl; // on another line getline(iFile, EmployeeName, '\t'); // repeat priming read getline(iFile, JobTitle, '\t'); // logic iFile >> EmployeeID; iFile.ignore(MAX, '\n'); } iFile.close(); // close input file return 0; }
Random Access • streampos p = direct.tellg(); For each file the system maintains the current position direct is a stream, tellg() returns the position # include <fstream> # include <iomanip> # include <stdlib>
Random Access • Try the following: main() { fstream io(“test.io”, ios::in | ios::out) if(!io){ cerr<< “failed to open”; exit(1); } streampos p1 = io.tellg(); io<<“top of file”; streampos p2 = io.tellg(); io<<“next to top of file”; char word[6]; io.seekg(p1); io >>setw(6) > word; cout<< word<<endl; }
Dynamic Stack Data Structure • class stack{ public: stack( int size){ s = new char[size]; max_len = size; top = empty;} void push(char c){s[++top] = c;} char pop(){return (s[top--]);} char top_of() const {return (s[top]);} boolean empty() const {return (boolean) (top ==EMPTY);} boolean full() const {return (boolean)(top== max_len -1);}
Stack data • private: enum {EMPTY = -1}; char * s; int max_len; int top; }; // end class
Using a Stack • in main() stack data(100); // allocates 100 elements
Copy Constructor • general form type::type(const type&) stack::stack(const stack& str) { s = new char[str.max_len]; max_len = str.max_len; top = str.top; memcpy(s,str.s,max_len); }
Stack class destructor • destruct the array ~stack(){ delete [ ] s;}
Now permit parameterised types • use template template <class TYPE> class stack{ public: stack():max_len(100),top(EMPTY) {s = new TYPE[100];} stack(int size):max_len(size),top(EMPTY) {s = new TYPE[size];} void push(TYPE c){s[++top];} TYPE pop(){return (s[top--]);} TYPE top_of{return(s[top]);} ..
Using the new class • angle brackets enclose type name: stack<char> stk_my; stack<int> st_2(100); stack<char*> st3(200);
Difficult syntax • when function outside current file: template<class TYPE> TYPE stack<TYPE>:: top_of() const{ return (s[top]);}