Objects and streams and files CS427: Elements of Software Engineering Lecture 6.2 (C++) 10am, 13 Feb 2012 CS427 Objects and streams and files 1/18
Today s topics 1 Recall...... Dynamic Memory Allocation... Encapsulation The stack example again 2 Constructor 3 Destructors 4 Streams as examples of Objects 5 code, cin methods manipulators 6 Files open CS427 Objects and streams and files 2/18
Recall...... Dynamic Memory Allocation In C++ dynamic memory allocation is achieved using new and delete. Example int *contents; contents = new int[20];... delete [] contents; Note: unlike calloc and malloc in C, new will work with any data type, including user-defined types such as class. Also, casting is not required. CS427 Objects and streams and files 3/18
Recall...... Encapsulation Encapsulation incorporating the data associated with an entity, and the methods of manipulating that data, into a single abstract data type. Usually, Public methods provide the interface to an object, while its internal state is represented by private data. In C++, encapsulation is usually achieved using the class construct.............................................................................. In today s class we ll quickly revise what we did in Lecture 4.2 and Lab 3: classes private and public members constructors Destructors, And then go onto streams as an example of a class. CS427 Objects and streams and files 4/18
Recall... The stack example again In Lecture 4.2 and Lab 3, we used a stack (LIFO queue) as an example of an bstract Data Type. Any function in the program can: declare a instance of the class stack. added to the top of the stack: s.push() ; removed from the top of the stack: s.pop(). These are the interfaces to the stack, and are public: For the stack itself, the following must be maintained: a character array contents[] a integer count of the number of items on the stack (top). These are private to the class. CS427 Objects and streams and files 5/18
Constructor We also introduced the idea of constructor. It is a public member function that has the same name as the class It is called automatically when an instance of the class is declared. It cannot have a return type. class stack private: char *contents; int top; public: stack(void); void push(char c); char pop(void ); }; stack::stack(void) top=0; contents = new char[max_stack]; } CS427 Objects and streams and files 6/18
Constructor This is a particularly basic example of a constructor. More commonly we pass arguments to the constructor that can be used Set the value of a data member; Dynamically size an array using new. However, one should still provide a default constructor (i.e., one with no arguments). class stack private: char *contents; int top; public: stack(void); stack(unsigned int StackSize); void push(char c); char pop(void ); }; stack::stack(void) top=0; contents = new char[max_stack]; } stack::stack(unsigned int StackSize) top=0; contents = new char[stacksize]; } CS427 Objects and streams and files 7/18
Destructors Complementing the idea of a constructor is a destructor. This function is called for a local object whenever it goes out of scope for a global object when the program ends. The name of the destructor is the same as the class, but preceded by a tilde: class stack private: char *contents; int top; public: stack(void ); stack(void ); void push(char c); char pop(); }; stack:: stack() delete [] contents; } CS427 Objects and streams and files 8/18
Streams as examples of Objects I/O means Input/Output. So far, we have taken input from the keyboard, typically using cin, and sent output to a terminal window, using cout. These are examples of streams: flows of data to or from your program. Moreover, they are examples of objects in C++. In this section, we ll study how to manipulate these streams in C++, including writing to and reading from files. But first, some more information about cout and cin. CS427 Objects and streams and files 9/18
code, cin methods The objects cout and cin are objects and are manipulated by their methods, i.e., public member functions and operators. Methods: width(int x) minimum number of characters for next output, fill(char x) character used to fill with in the case that the width needs to be elongated to fill the minimum. precision(int x) sets the number of significant digits for floating-point numbers. CS427 Objects and streams and files 10/18
code, cin methods See 01cinANDcout.cpp Code width for (int i=65; i<123; i++) cout.width(8); cout << i; cout.width(3); cout << (char) i; if ( (i%5) == 4) cout << endl; } Output 65 A 66 B 67 C... 70 F 71 G 72 H... 75 K 76 L 77 M... 80 P 81 Q 82 R... 85 U 86 V 87 W 90 Z 91 [ 92 \ 95 _ 96 97 a 100 d 101 e 102 f 105 i 106 j 107 k 110 n 111 o 112 p 115 s 116 t 117 u 120 x 121 y 122 CS427 Objects and streams and files 11/18
code, cin methods Code width, fill cout.fill( 0 ); for (int i=0; i<10000; i+= rand()%2000) cout.width(6); cout << i <<endl; } Output 000000 001383 002269 003046 003961 005754 006089 007475 007967 008616 CS427 Objects and streams and files 12/18
code, cin methods Code precision double Pi=3.1415926535; for (int i=1; i<=10; i++) cout.precision(i); cout << Pi (correct to << i << digits) is << Pi << endl; } Output Pi (correct to 1 digits) is 3 Pi (correct to 2 digits) is 3.1 Pi (correct to 3 digits) is 3.14 Pi (correct to 4 digits) is 3.142 Pi (correct to 5 digits) is 3.1416 Pi (correct to 6 digits) is 3.14159 Pi (correct to 7 digits) is 3.141593 Pi (correct to 8 digits) is 3.1415927 Pi (correct to 9 digits) is 3.14159265 Pi (correct to 10 digits) is 3.141592654 CS427 Objects and streams and files 13/18
code, cin manipulators setw like width left Left justifies output in field width. Used after setw(n). right right justify. endl inserts a newline into the stream and calls flush. flush forces an output stream to write any buffered characters dec changes the output format of number to be in decimal format oct octal format hex hexadecimal format showpoint show the decimal point and some zeros with whole numbers Others: setprecision(n), fixed, scientific, boolalpha, noboolalpha,... Need to include iomanip CS427 Objects and streams and files 14/18
code, cin manipulators All of the C++ programs we have looked at so far took their input from the standard input stream: this was usually the keyboard. Example: cout << Enter an inteter: ; cin >> i; Although, for example, the standard input stream can be redirected to a file, it is usually necessary to open a file from within the program and take the data from there. The same is true for writing to a file. To do either of these takes in C++ we create a file stream and use it just as we would cin or cout. CS427 Objects and streams and files 15/18
Files When working with files, we need to include the fstream header file. To read from a file, declare an object of type ifstream; to write to a file, declare an object of type ofstream. Open the file by calling the open() member function. To read a single character, can use InFile.get ) 1 include iostream > 2 include fstream > 3 include c s t d l i b > 5 using namespace std ; 02CountChars.cpp 7 i n t main ( void ) 8 9 i f s t r e a m I n F i l e ; 10 ofstream OutFile ; 11 char InFileName [ 30]= CPlusPlusTerms. t x t ; 12 char c ; 14 cout Processing the contents of 15 InFileName endl ; 16 cout See Output. t x t f o r more i n f o 17 endl ; 18 I n F i l e. open ( InFileName ) ; 19 OutFile. open ( Output. t x t ) ; 21 i n t i =0; 22 I n F i l e. get ( c ) ; CS427 Objects and streams and files 16/18
Files If there are no more characters left in the input stream, then InFile.eof() evaluates as true. Use the steam objects just as you would use cin or cout: InFile >> data or OutFile << data. Close the files: InFile.close(), OutFile.close() 02CountChars.cpp (continued) 22 while ( I n F i l e. eof ( ) ) 23 24 i ++; 25 I n F i l e. get ( c ) ; 26 } 28 OutFile InFileName contains 29 i characters n ; 32 I n F i l e. close ( ) ; 33 OutFile. close ( ) ; 35 return ( 0 ) ; 36 } CS427 Objects and streams and files 17/18
Files open Note that the method open works differently for ifstream and ofstream; InFile.open Opens an existing file for reading, OutFile.open Opens a file for writing. If it already exists, its contents are overwritten. To open an existing file and append to its contents, use OutFile.open( Output.txt, ios::app); If the open call fails, then the method fail() returns true. So you should always include something like to following after opening a file: if (InFile.fail()) cerr << Error - can t open << InFileName << endl; exit(1); } CS427 Objects and streams and files 18/18