Consider the following example where a base class has been derived by other two classes:

Similar documents
Object Oriented Programming Using C++ UNIT-3 I/O Streams

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

C++ Programming Lecture 10 File Processing

Chapte t r r 9

Chapter-12 DATA FILE HANDLING

CS Programming2 1 st Semester H Sheet # 8 File Processing. Princess Nora University College of Computer and Information Sciences

Unit-V File operations

Object Oriented Programming In C++

After going through this lesson, you would be able to: store data in a file. access data record by record from the file. move pointer within the file

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1]

C++ files and streams. Lec 28-31

CS2141 Software Development using C/C++ Stream I/O

C++ does not, as a part of the language, define how data are sent out and read into the program

C++ Binary File I/O. C++ file input and output are typically achieved by using an object of one of the following classes:

Chapter 3 - Notes Input/Output

I/O Streams and Standard I/O Devices (cont d.)

C++ Input/Output: Streams

Page 1

Streams - Object input and output in C++

C++ Quick Guide. Advertisements

Computer programs are associated to work with files as it helps in storing data & information permanently. File - itself a bunch of bytes stored on

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Streams in C++ Stream concept. Reference information. Stream type declarations

Module 11 The C++ I/O System

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7. Data File Handling

DATA FILE HANDLING FILES. characters (ASCII Code) sequence of bytes, i.e. 0 s & 1 s

Lecture 9. Introduction

Writing a Good Program. 7. Stream I/O

File I/O Christian Schumacher, Info1 D-MAVT 2013

IS 0020 Program Design and Software Tools

Input and Output File (Files and Stream )

Developed By : Ms. K. M. Sanghavi

BITG 1113: Files and Stream LECTURE 10

ios ifstream fstream

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

Fall 2017 CISC/CMPE320 9/27/2017

UEE1303(1070) S 12 Object-Oriented Programming in C++

Random File Access. 1. Random File Access

Week 3: File I/O and Formatting 3.7 Formatting Output

Advanced I/O Concepts

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file.

UNIT- 3 Introduction to C++

Objects and streams and files CS427: Elements of Software Engineering

COMP322 - Introduction to C++

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York

Fundamentals of Programming Session 27

10/23/02 21:20:33 IO_Examples

Introduction to C++ (Extensions to C)

Downloaded from

COMP322 - Introduction to C++

Chapter 12: Advanced File Operations

Chapter 14 Sequential Access Files

UNIT V FILE HANDLING

QUESTION BANK. SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING

Chapter 8 File Processing

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Study Material for Class XII. Data File Handling

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay

We can even use the operator << to chain the output request as:

Streams contd. Text: Chapter12, Big C++

System Design and Programming II

Advanced File Operations. Review of Files. Declaration Opening Using Closing. CS SJAllan Chapter 12 2

EP241 Computing Programming

Object Oriented Programming

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Fig: iostream class hierarchy

More File IO. CIS 15 : Spring 2007

File handling Basics. Lecture 7

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I.

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Lecture 5 Files and Streams

Getting started with C++ (Part 2)

Chapter 21 - C++ Stream Input/Output

We will exclusively use streams for input and output of data. Intro Programming in C++

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

Input/Output Streams: Customizing

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

Polymorphism Part 1 1

Today in CS162. External Files. What is an external file? How do we save data in a file? CS162 External Data Files 1

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

Chapter 12. Streams and File I/O

Introduction. Lecture 5 Files and Streams FILE * FILE *

basic_fstream<chart, traits> / \ basic_ifstream<chart, traits> basic_ofstream<chart, traits>

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams

BITG 1233: Introduction to C++

Lecture 3 The character, string data Types Files

C++ Input/Output Chapter 4 Topics

Chapter 21 - C++ Stream Input/Output

Stream States. Formatted I/O

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

Come and join us at WebLyceum

by Pearson Education, Inc. All Rights Reserved. 2

DISK FILE PROGRAM. ios. ofstream

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Transcription:

Class : BCA 3rd Semester Course Code: BCA-S3-03 Course Title: Object Oriented Programming Concepts in C++ Unit IV Polymorphism The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance. C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function. Consider the following example where a base class has been derived by other two classes: #include <iostream> using namespace std; class Shape protected: int width, height; public: Shape( int a = 0, int b = 0) width = a; height = b; ; int area() cout << "Parent class area :" <<endl; return 0; class Rectangle: public Shape public: Rectangle( int a = 0, int b = 0):Shape(a, b) int area () cout << "Rectangle class area :" <<endl; return (width * height); ; class Triangle: public Shape public: Triangle( int a = 0, int b = 0):Shape(a, b) int area () cout << "Triangle class area :" <<endl;

; return (width * height / 2); // Main function for the program int main( ) Shape *shape; Rectangle rec(10,7); Triangle tri(10,5); // store the address of Rectangle shape = &rec; // call rectangle area. shape->area(); // store the address of Triangle shape = &tri; // call triangle area. shape->area(); return 0; When the above code is compiled and executed, it produces the following result: Parent class area Parent class area The reason for the incorrect output is that the call of the function area() is being set once by the compiler as the version defined in the base class. This is called static resolution of the function call, or static linkage - the function call is fixed before the program is executed. This is also sometimes called early binding because the area() function is set during the compilation of the program. But now, let's make a slight modification in our program and precede the declaration of area() in the Shape class with the keyword virtual so that it looks like this: class Shape protected: int width, height; public: Shape( int a = 0, int b = 0) width = a; height = b;

virtual int area() cout << "Parent class area :" <<endl; return 0; ; After this slight modification, when the previous example code is compiled and executed, it produces the following result: Rectangle class area Triangle class area This time, the compiler looks at the contents of the pointer instead of it's type. Hence, since addresses of objects of tri and rec classes are stored in *shape the respective area() function is called. As you can see, each of the child classes has a separate implementation for the function area(). This is how polymorphism is generally used. You have different classes with a function of the same name, and even the same parameters, but with different implementations. Virtual Function A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class as virtual function, with another version in a derived class, signals to the compiler that we don't want static linkage for this function. What we do want is the selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding. Pure Virtual Functions It's possible that you'd want to include a virtual function in a base class so that it may be redefined in a derived class to suit the objects of that class, but that there is no meaningful definition you could give for the function in the base class. We can change the virtual function area() in the base class to the following: class Shape protected: int width, height; public: Shape( int a = 0, int b = 0) width = a; height = b; ; // pure virtual function virtual int area() = 0;

The = 0 tells the compiler that the function has no body and above virtual function will be called pure virtual function. Early binding Most of the function calls the compiler encounters will be direct function calls. A direct function call is a statement that directly calls a function. For example: #include <iostream> void PrintValue(int nvalue) std::cout << nvalue; int main() PrintValue(5); // This is a direct function call return 0; Direct function calls can be resolved using a process known as early binding. Early binding (also called static binding) means the compiler is able to directly associate the identifier name (such as a function or variable name) with a machine address. Remember that all functions have a unique machine address. So when the compiler encounters a function call, it replaces the function call with a machine language instruction that tells the CPU to jump to the address of the function. Let s take a look at a simple calculator program that uses early binding: #include <iostream> using namespace std; int Add(int nx, int ny) return nx + ny; int Subtract(int nx, int ny) return nx - ny; int Multiply(int nx, int ny) return nx * ny; int main() int nx; cout << "Enter a number: "; cin >> nx;

int ny; cout << "Enter another number: "; cin >> ny; int noperation; do cout << "Enter an operation (0=add, 1=subtract, 2=multiply): "; cin >> noperation; while (noperation < 0 noperation > 2); int nresult = 0; switch (noperation) case 0: nresult = Add(nX, ny); break; case 1: nresult = Subtract(nX, ny); break; case 2: nresult = Multiply(nX, ny); break; cout << "The answer is: " << nresult << endl; return 0; Because Add(), Subtract(), and Multiply() are all direct function calls, the compiler will use early binding to resolve the Add(), Subtract(), and Multiply() function calls. The compiler will replace the Add() function call with an instruction that tells the CPU to jump to the address of the Add() function. The same holds true for Subtract() and Multiply(). Abstract Class Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes are used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must provide definition to the pure virtual function, otherwise they will also become abstract class. Characteristics of Abstract Class Abstract class cannot be instantiated, but pointers and refrences of Abstract class type can be created. Abstract class can have normal functions and variables along with a pure virtual function. Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface. Classes inheriting an Abstract Class must implement all pure virtual functions, or else they will become Abstract too. Pure Virtual Functions Pure virtual Functions are virtual functions with no definition. They start with virtual keyword and ends with= 0. Here is the syntax for a pure virtual function, virtual void f() = 0;

Example of Abstract Class class Base //Abstract base class public: virtual void show() = 0; //Pure Virtual Function ; class Derived:public Base public: void show() cout << "Implementation of Virtual Function in Derived class"; ; int main() Base obj; Base *b; Derived d; b = &d; b->show(); //Compile Time Error Output : Implementation of Virtual Function in Derived class In the above example Base class is abstract, with pure virtual show() function, hence we cannot create object of base class. Data File Handling In C++ File. The information / data stored under a specific name on a storage device, is called a file. Stream. It refers to a sequence of bytes. Text file. It is a file that stores information in ASCII characters. In text files, each line of text is terminated with a special character known as EOL (End of Line) character or delimiter character. When this EOL character is read or written, certain internal translations take place. Binary file. It is a file that contains information in the same format as it is held in memory. In binary files, no delimiters are used for a line and no translations occur here. Classes for file stream operation ofstream: Stream class to write on files ifstream: Stream class to read from files fstream: Stream class to both read and write from/to files. Opening a file

OPENING FILE USING CONSTRUCTOR ofstream outfile("sample.txt"); //output only ifstream infile( sample.txt ); //input only OPENING FILE USING open() method Stream-object.open( filename, mode) ofstream outfile; outfile.open("sample.txt"); ifstream infile; infile.open("sample.txt"); File mode parameter Meaning ios::app Append to end of file ios::ate go to end of file on opening ios::binary file open in binary mode ios::in open file for reading only ios::out open file for writing only ios::nocreate open fails if the file does not exist ios::noreplace open fails if the file already exist ios::trunc delete the contents of the file if it exist The mode parameter can have different interpretations as under All these flags can be combined using the bitwise operator OR ( ). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open(): fstream file; file.open ("example.bin", ios::out ios::app ios::binary); Closing File

outfile.close(); infile.close(); INPUT AND OUTPUT OPERATION put() and get() function the function put() writes a single character to the associated stream. Similarly, the function get() reads a single character form the associated stream. example : file.get(ch); file.put(ch); write() and read() function write() and read() functions write and read blocks of binary data. example: file.read((char *)&obj, sizeof(obj)); file.write((char *)&obj, sizeof(obj)); ERROR HANDLING FUNCTION FUNCTION RETURN VALUE AND MEANING eof() returns true (non zero) if end of file is encountered while reading; otherwise return false(zero) fail() return true when an input or output operation has failed bad() returns true if an invalid operation is attempted or any unrecoverable error has occurred. good() returns true if no error has occurred.

File Pointers And Their Manipulation All i/o streams objects have, at least, one internal stream pointer: ifstream, like istream, has a pointer known as the get pointer that points to the element to be read in the next input operation. ofstream, like ostream, has a pointer known as the put pointer that points to the location where the next element has to be written. Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived from both istream and ostream). These internal stream pointers that point to the reading or writing locations within a stream can be manipulated using the following member functions: seekg() moves get pointer(input) to a specified location seekp() moves put pointer (output) to a specified location tellg() gives the current position of the get pointer tellp() gives the current position of the put pointer The other prototype for these functions is: seekg(offset, refposition ); seekp(offset, refposition ); The parameter offset represents the number of bytes the file pointer is to be moved from the location specified by the parameter refposition. The refposition takes one of the following three constants defined in the ios class. ios::beg start of the file ios::cur current position of the pointer ios::end end of the file example: file.seekg(-10, ios::cur);

Basic Operation On Text File In C++ File I/O is a five-step process: 1. Include the header file fstream in the program. 2. Declare file stream object. 3. Open the file with the file stream object. 4. Use the file stream object with >>, <<, or other input/output functions. 5. Close the files. Following program shows how the steps might appear in program. Program to write in a text file #include <fstream> using namespace std; int main() ofstream fout; fout.open("out.txt"); char str[300] = "Time is a great teacher but unfortunately it kills all its pupils. Berlioz"; //Write string to the file. fout << str; fout.close(); return 0; Program to read from text file and display it #include<fstream> #include<iostream> using namespace std; int main() ifstream fin; fin.open("out.txt"); char ch; while(!fin.eof()) fin.get(ch);

cout << ch; fin.close(); return 0; Program to count number of characters. #include<fstream> #include<iostream> using namespace std; int main() ifstream fin; fin.open("out.txt"); int count = 0; char ch; while(!fin.eof()) fin.get(ch); count++; cout << "Number of characters in file are " << count; fin.close(); return 0; Program to count number of words #include<fstream> #include<iostream> using namespace std; int main() ifstream fin; fin.open("out.txt"); int count = 0; char word[30]; while(!fin.eof())

fin >> word; count++; cout << "Number of words in file are " << count; fin.close(); return 0; Program to count number of lines #include<fstream> #include<iostream> using namespace std; int main() ifstream fin; fin.open("out.txt"); int count = 0; char str[80]; while(!fin.eof()) fin.getline(str,80); count++; cout << "Number of lines in file are " << count; fin.close(); return 0; Program to copy contents of file to another file. #include<fstream> using namespace std; int main() ifstream fin; fin.open("out.txt"); ofstream fout; fout.open("sample.txt");

char ch; while(!fin.eof()) fin.get(ch); fout << ch; fin.close(); fout.close(); return 0; Basic Operation On Binary File In C++ When data is stored in a file in the binary format, reading and writing data is faster because no time is lost in converting the data from one format to another format. Such files are called binary files. This following program explains how to create binary files and also how to read, write, search, delete and modify data from binary files. #include<iostream> #include<fstream> #include<cstdio> using namespace std; class Student int admno; char name[50]; public: void setdata() cout << "\nenter admission no. "; cin >> admno; cout << "Enter name of student "; cin.getline(name,50); void showdata() cout << "\nadmission no. : " << admno; cout << "\nstudent Name : " << name; int retadmno() return admno;

; /* * function to write in a binary file. */ void write_record() ofstream outfile; outfile.open("student.dat", ios::binary ios::app); Student obj; obj.setdata(); outfile.write((char*)&obj, sizeof(obj)); outfile.close(); /* * function to display records of file */ void display() ifstream infile; infile.open("student.dat", ios::binary); Student obj; while(infile.read((char*)&obj, sizeof(obj))) obj.showdata(); infile.close(); /* * function to search and display from binary file */ void search(int n) ifstream infile; infile.open("student.dat", ios::binary);

Student obj; while(infile.read((char*)&obj, sizeof(obj))) if(obj.retadmno() == n) obj.showdata(); infile.close(); /* * function to delete a record */ void delete_record(int n) Student obj; ifstream infile; infile.open("student.dat", ios::binary); ofstream outfile; outfile.open("temp.dat", ios::out ios::binary); while(infile.read((char*)&obj, sizeof(obj))) if(obj.retadmno()!= n) outfile.write((char*)&obj, sizeof(obj)); infile.close(); outfile.close(); remove("student.dat"); rename("temp.dat", "student.dat"); /* * function to modify a record */ void modify_record(int n) fstream file; file.open("student.dat",ios::in ios::out);

Student obj; while(file.read((char*)&obj, sizeof(obj))) if(obj.retadmno() == n) cout << "\nenter the new details of student"; obj.setdata(); int pos = -1 * sizeof(obj); file.seekp(pos, ios::cur); file.write((char*)&obj, sizeof(obj)); file.close(); int main() //Store 4 records in file for(int i = 1; i <= 4; i++) write_record(); //Display all records cout << "\nlist of records"; display(); //Search record cout << "\nsearch result"; search(100); //Delete record delete_record(100); cout << "\nrecord Deleted"; //Modify record cout << "\nmodify Record 101 "; modify_record(101); return 0; I/O Manipulators Manipulators are the most common way to control output formating.

I/O manipulators that take parameters are in the <iomanip> include file. Default Floating-point Format Unless you use I/O manipulators (or their equivalent), the default format for each floating-point number depends on its value. No decimal point: 1.0000 prints as 1 No trailing zeros: 1.5000 prints as 1.5 Scientific notation for large/small numbers: 1234567890.0 prints as 1.23457e+09 Example #include <iostream> #include <iomanip> using namespace std; int main() const float tenth = 0.1; const float one = 1.0; const float big = 1234567890.0; cout << "A. " << tenth << ", " << one << ", " << big << endl; cout << "B. " << fixed << tenth << ", " << one << ", " << big << endl; cout << "C. " << scientific << tenth << ", " << one << ", " << big << endl; cout << "D. " << fixed << setprecision(3) << tenth << ", " << one << ", " << big << endl; cout << "E. " << setprecision(20) << tenth << endl; cout << "F. " << setw(8) << setfill('*') << 34 << 45 << endl; cout << "G. " << setw(8) << 34 << setw(8) << 45 << endl; return 0; produces this output (using DevC++ 4.9.8.0): A. 0.1, 1, 1.23457e+009 B. 0.100000, 1.000000, 1234567936.000000 C. 1.000000e-001, 1.000000e+000, 1.234568e+009 D. 0.100, 1.000, 1234567936.000 E. 0.1000000014901161 F. ******3445 G. ******34******45 The following are the list of standard manipulator used in a C++ program. To carry out the operations of these manipulator functions in a user program, the header file input and output manipulator <iomanip.h> must be included. Predefined manipulators

Following are the standard manipulators normally used in the stream classes: endl hex, dec, oct setbase setw setfill setprecision ends ws flush setiosflags resetiosflags (a) Endl the endl is an output manipulator to generate a carriage return or line feed character. The endl may be used several times in a C++ statement. For example, (1) cout << a << endl << b << endl; (2) cout << a = << a << endl; cout << b = << b << endl; A program to display a message on two lines using the endl manipulator and the corresponding output is given below. / / using endl manipulator #include <iostream.h> Void main (void) cout << My name is Komputer ; cout << endl;

cout << many greetings to you ; Output of the above program My name is Komputer Many greetings to you The endl is the same as the non-graphic character to generate line feed (\n). A program to illustrate the usage of line feed character and the endl manipulator and the corresponding output are given below. #include <iostream.h> void main ( ) int a; a = 20; cout << a = << a << endl; cout << a = << a << \n ; cout << a = << a << \n ; Output of the above program a = 20 a = 20 a = 20 (b) Setbase() The setbase() manipulator is used to convert the base of one numeric value into another base. Following are the common base converters in C++. dec - decimal base (base = 10) hex - hexadecimal base (base = 16) oct - octal base (base = 8)

In addition to the base conversion facilities such as to bases dec, hex and oct, the setbase()manipulator is also used to define the base of the numeral value of a variable. The prototype ofsetbase() manipulator is defined in the iomanip.h header file and it should be include in user program. The hex, dec, oct manipulators change the base of inserted or extracted integral values. The original default for stream input and output is dec. PROGRAM A program to show the base of a numeric value of a variable using hex, oct and dec manipulator functions. / / using dec, hex, oct manipulator #include <iostream.h> Void main (void) int value; cout << Enter number << endl; cin >> value; cout << Decimal base = << dec << value << endl; cout << Hexadecimal base = << hex << value << endl; cout << Octal base = << oct << value << endl; Output of the above program Enter number 10 Decimal base = 10 Hexadecimal base = a Octal base = 12 PROGRAM A program to show the base of a numeric value of a variable using setbase manipulator function. / /using setbase manipulator

#include <iostream.h> #include <iomanip.h> void main (void) int value cout << Enter number << endl; cin >> value; cout << decimal base = << setbase (10) cout << value << endl; cout << hexadecimal base = << setbase (16); cout << value << endl; cout << Octal base = << setbase (8) << value << endl; The output of this program is the same as the output of program 2.2 (c) Setw () The setw ( ) stands for the set width. The setw ( ) manipulator is used to specify the minimum number of character positions on the output field a variable will consume. The general format of the setw manipulator function is setw( int w ) Which changes the field width to w, but only for the next insertion. The default field width is 0. For example, cout << setw (1) << a << endl; cout << setw (10) << a << endl; Between the data variables in C++ space will not be inserted automatically by the compiler. It is upto a programmer to introduce proper spaces among data while displaying onto the screen. PROGRAM A program to display the content of a variable without inserting any space. #include <iostream.h>

void main (void) int a,b; a = 200; b = 300; cout << a << b << endl; Output of the above program 200300 PROGRAM A program to insert a tab character between two variables while displaying the content onto the screen. / /using setw manipulator #include <iostream.h> #include <iomanip.h> void main (void) int a,b; a = 200; b = 300; cout << a << \t << b << endl; Output of the above program 200 300 PROGRAM A program to display the data variables using setw manipulator functions.

/ /using setw manipulator #include <iostream.h> #include <iomanip.h> void main (void) int a,b; a = 200; b = 300; cout << setw (5) << a << setw (5) << b << endl; cout << setw (6) << a << setw (6) << b << endl; cout << setw (7) << a << setw (7) << b << endl; cout << setw (8) << a << setw (8) << b << endl; Output of the above program 200 300 200 300 200 300 200 300 (d) Setfill() The setfill ( ) manipulator function is used to specify a different character to fill the unused field width of the value. The general syntax of the setfill ( ) manipulator is setfill( char f) which changes the fill character to f. The default fill character is a space. For example, setfill (. ) ; / / fill a dot (. ) character setfill ( * ) / / fill a asterisk (*) character PROGRAM

A program to illustrate how a character is filled in filled in the unused field width of the value of the data variable. / /using setfill manipulator #include <iostream.h> #include <iomanip.h> void main ( void) int a,b; a = 200; b = 300; cout << setfill ( * ); cout << setw (5) << a << setw (5) << b << endl; cout << setw (6) << a << setw (6) << b << endl; cout << setw (7) << a << setw (7) << b << endl; cout << setw (8) << a << setw (8) << b << endl; Output of the above program **200**300 ***200***300 ****200****300 *****200*****300 (e) Setprecision() The setprecision ( ) is used to control the number of digits of an output stream display of a floating point value. The setprecision ( ) manipulator prototype is defined in the header file <iomanip.h>. The general syntax of the setprecision manipulator is Setprecision (int p) Which sets the precision for floating point insertions to p. The default precision is 6 PROGRAM

A program to use the setprecision manipulator function while displaying a floating point value onto the screen. / /using setprecision manipulator #include <iostream.h> #include <iomanip.h> void main (void) float a,b,c; a = 5; b = 3; c = a/b; cout << setprecision (1) << c << endl; cout << setprecision (2) << c << endl; cout << setprecision (3) << c << endl; cout << setprecision (4) << c << endl; cout << setprecision (5) << c << endl; cout << setprecision (6) << c << endl; Output of the program 1.7 1.67 1.667 1.6667 1.66667 1.666667

(f) Ends The ends is a manipulator used to attach a null terminating character ( \0 ) at the end of a string. The ends manipulator takes no argument whenever it is invoked. This causes a null character to the output. PROGRAM A program to show how a null character is inserted using ends manipulator while displaying a string onto the screen. / /using ends manipulator #include <iostream.h> #include <iomanip.h> Void main ( ) int number = 231; cout << \ << number = << number << ends; cout << \ << endl; Output of the above program number = 123 (g) Ws The manipulator function ws stands for white space. It is used to ignore the leading white space that precedes the first field. / /using ws manipulator #include <iostream.h> #include <iomanip.h> Void main ( ) char name [100] cout << enter a line of text \n ; cin >> ws; cin >> name;

cout << typed text is = << name << endl; Output of the program enter a line of text this is a text typed text is = this (b) Flush The flush member function is used to cause the stream associated with the output to be completed emptied. This argument function takes no input prameters whenever it is invoked. For input on the screen, this is not necessary as all output is flushed automatically. However, in the case of a disk file begin copied to another, it has to flush the output buffer prior to rewinding the output file for continued use. The function flush ( ) does not have anything to do with flushing the input buffer. / /using flush member function #include <iostream.h> #include <iomanip.h> void main ( ) cout << My name is Komputer \n ; cout << many greetings to you \n ; cout. flush ( ) ; The hex, dec, oct, ws, endl, ends and flush manipulators are defined in stream.h. The other manipulators are defined in iomanip.h which must be included in any program that employs them. (i) Setiosflags and Resetiosflags The setiosflags manipulator function is used to control different input and output settings. The I/O stream maintains a collection of flag bits. The setiosflags manipulator performs the same function as the setf function. The flags represented by the set bits in f are set. The general syntax of the setiosflags is, setiosflags ( long h)

The restiosflags manipulator performs the same function as that of the resetf function. The flags represented by the set bits in f are reset. The general syntax of the resetiosflags is a follows, Resetiosflags (long f) PROGRAM A program to demonstrate how setiosflags is set while displaying the base of a numeral. / /using setiosflags of basefield #include <iostream.h> #include <iomanip.h> void main (void) int value; cout << enter a number \n ; cin >> value; cout << setiosflags (ios : : showbase) ; cout << setiosflags (ios : : dec) ; cout << decimal = << value << endl; cout << setiosflags (ios : : hex) ; cout << hexadecimal = << value << endl ; cout << setiosflags (ios : : oct) ; cout << octal = << value << endl ; Output of the above program enter a number 10 decimal = 10

hexadecimal = 0xa octal = 012