Object Oriented Programming In C++

Similar documents
Unit-V File operations

Chapter-12 DATA FILE HANDLING

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

C++ Programming Lecture 10 File Processing

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

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

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

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

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

Chapte t r r 9

Developed By : Ms. K. M. Sanghavi

C++ files and streams. Lec 28-31

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

UNIT V FILE HANDLING

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

by Pearson Education, Inc. All Rights Reserved. 2

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

Study Material for Class XII. Data File Handling

ios ifstream fstream

Random File Access. 1. Random File Access

Module 11 The C++ I/O System

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

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

Chapter 8 File Processing

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

Chapter 14 Sequential Access Files

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

Page 1

IS 0020 Program Design and Software Tools

Programming II with C++ (CSNB244) Lab 10. Topics: Files and Stream

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

Lecture 9. Introduction

Streams - Object input and output in C++

Writing a Good Program. 7. Stream I/O

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

COMP322 - Introduction to C++

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

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

Fall 2017 CISC/CMPE320 9/27/2017

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

BITG 1113: Files and Stream LECTURE 10

Object Oriented Programming CS250

C++ Input/Output: Streams

Chapter 12: Advanced File Operations

Input and Output File (Files and Stream )

Advanced I/O Concepts

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

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

Chapter 3 - Notes Input/Output

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

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

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

Module C++ I/O System Basics

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

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

C++ How to Program 14.6

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

Fundamentals of Programming Session 27

by Pearson Education, Inc. All Rights Reserved. 2

Fig: iostream class hierarchy

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

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

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

Streams contd. Text: Chapter12, Big C++

Standard File Pointers

System Design and Programming II

Applications with Files, Templates

More File IO. CIS 15 : Spring 2007

Stream States. Formatted I/O

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

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

CS201 Latest Solved MCQs

Downloaded from

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

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

Computer Programming Unit v

VuZs Team's Work. CS201 Spring Solved by vuzs Team with Reference Written by Administrator Wednesday, 19 May :52

DISK FILE PROGRAM. ios. ofstream

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

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

What we will learn about this week:

CS3157: Advanced Programming. Outline

EP241 Computing Programming

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

All About: File I/O in C++ By Ilia Yordanov, ; C++ Resources

Objects and streams and files CS427: Elements of Software Engineering

Lecture 5 Files and Streams

Chapter 3: Input/Output

by Pearson Education, Inc. All Rights Reserved. 2

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

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

COMP322 - Introduction to C++

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

Input/output. Remember std::ostream? std::istream std::ostream. std::ostream cin std::istream. namespace std { class ostream { /*...

UNIT V FILE HANDLING

CS201 Solved MCQs.

Input/Output Streams: Customizing

Getting started with C++ (Part 2)

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

Transcription:

C++ Question Bank Page 1 Object Oriented Programming In C++ 1741059 to 1741065 Group F Date: 31 August, 2018 CIA 3 1. Briefly describe the various forms of get() function supported by the input stream. Give example for each of them. [1741059] gets() Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached. The newline character, if found, is not copied into str. A terminating null character is automatically appended after the characters copied to str. Example: int main() char string [256]; printf ("Insert your full address: "); gets (string); printf ("Your address is: %s\n",string); return 0; fgets() Get string from stream Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the endof-file is reached, whichever happens first. A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str. A terminating null character is automatically appended after the characters copied to str. Example :

C++ Question Bank Page 2 int main() FILE * pfile; char mystring [100]; pfile = fopen ("myfile.txt", "r"); if (pfile == NULL) perror ("Error opening file"); else if ( fgets (mystring, 100, pfile)!= NULL ) puts (mystring); fclose (pfile); return 0; getchar() Returns the next character from the standard input (stdin). It is equivalent to calling getc with stdin as argument. Example: int main () int c; puts ("Enter text. Include a dot ('.') in a sentence to exit:"); do c=getchar(); putchar (c); while (c!= '.'); return 0; scanf() Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string. Example:

C++ Question Bank Page 3 int main () char str [80]; int i; printf ("Enter your surname: "); scanf ("%79s",str); printf ("Enter your age: "); scanf ("%d",&i); printf ("Mr. %s, %d years old.\n",str,i); printf ("Enter a hexadecimal number: "); scanf ("%x",&i); printf ("You have entered %#x (%d).\n",i,i); return 0; 2. Create a single manipulator to provide the following output specifications for printing float values: a) 16 columns width b) Right-justified c) Four digits precision. [1741064] cout << setprecision(4)<< setwidth(16)<< f <<right; 3. Briefly explain filling and padding functions in C++. [1741059] get: char fill() const; This form returns the fill character. The fill character is the character used by output insertion functions to fill spaces when padding results to the field width. set char fill (char fillch);

C++ Question Bank Page 4 This form sets fillch as the new fill character and returns the fill character used before the call. The parametric manipulator setfill can also be used to set the fill character. 4. Why is it necessary to include the file iostream in all C++ programs? [1741060] iostream.h is a file containing code for input/output operations. You need to include iostream.h so that the compiler knows about the word cout and cin, which appears a couple of lines below. 5. Compare set(), fill() and precision functions with example. [1741059] set() Sets are containers that store unique elements following a specific order. In a set, the value of an element also identifies it (the value is itself the key) and each value must be unique. The value of the elements in a set cannot be modified once in the container (the elements are always const) but they can be inserted or removed from the container. Internally, the elements in a set are always sorted following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare). Sets are typically implemented as binary search trees. fill() The fill function assigns the value val to all the elements in the range [begin, end), where begin is the initial position and end is the last position. Example : int main () vector<int> vect(8); // calling fill to initialize values in the

C++ Question Bank Page 5 // range to 4 fill(vect.begin() + 2, vect.end() - 1, 4); for (int i=0; i<vect.size(); i++) cout << vect[i] << " "; return 0; Precision functions streamsize precision() const; This returns the value of the current floating-point precision field for the stream. streamsize precision (streamsize prec); This form also sets it to a new value. Set decimal precision Sets the decimal precision to be used to format floating-point values on output operations. 6. Briefly explain the importance of cin and cout in C++. [1741060] The Standard Output Stream (cout) The predefined object cout is an instance of ostream class. The cout object is said to be "connected to" the standard output device, which usually is the display screen. The cout is used in conjunction with the stream insertion operator, which is written as << which are two less than signs. The Standard Input Stream (cin) The predefined object cin is an instance of istream class. The cin object is said to be attached to the standard input device, which usually is the keyboard. The cin is used in conjunction with the stream extraction operator, which is written as >> which are two greater than signs.

C++ Question Bank Page 6 7. Compare input and output stream with a diagram. [1741061] Input Stream Input stream objects can read and interpret input from sequences of characters. cin is the instance of the class istream and is used to read input from the standard input device which is usually keyboard. The extraction operator(>>) is used along with the object cin for reading inputs. Output Stream Output stream objects can write sequences of characters and represent other kinds of data. cout is the instance of the ostream class. cout is used to produce output on the standard output device which is usually the display screen. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator (<<).

C++ Question Bank Page 7 8. Write a program to print the numeral and the square root of the numeral from 1 to 5 by using the precision setting. [1741063] Theory: The precision of a floating-point number defines how many significant digits it can represent. We use the manipulator setprecision(int) to display numbers up to a specified decimal digit. setprecision(int) is declared in header <iomanip> setprecision must take an integer as an argument, which specifies the number of significant digits the output should be in cout has a default precision of 6, so it truncates anything after 6 significant figures A variation of this can be done using keywords fixed and scientific. The keyword fixed is used to keep the number of digits that come after the decimal point fixed. This does not count significant figures, but the number of digits that occur after the decimal point. It has to be the same as specified by the setprecision() manipulator, so the statement cout<<fixed<<setprecision(5)<<a<<endl; where a holds the value 7.5 will print 7.5000. Notice how there has to be 5 digits after the decimal so it makes up with 0s for lacking digits.similarly, if a is 123, it would print 123.00000. Program: /*Program to demonstrate setprecision manipulator *Author: Vijay Kumar Prakash *Date: 02/August/2018/Sunday*/ #include <iostream> #include <iomanip> predefined library #include <math.h> using namespace std; //setprecision function is defined in this int main () int i;

C++ Question Bank Page 8 double pi,fraction; pi=22.0/7.0; cout<<"using DEFAULT PRECISION:\n"; cout<<"22/7 (PI) IS "<<pi<<endl; fraction=1.0/3.0; cout<<"1/3 IS "<<fraction<<endl; cout<<"\nusing SET PRECISION:\n"; fraction=43.0/8; cout<<setprecision(2)<<fraction<<endl; cout<<setprecision(9)<<fraction<<endl; cout<<"\nusing FIXED SET PRECISION:\n"; cout<<fixed; cout<<setprecision(1)<<fraction<<endl; cout<<setprecision(5)<<fraction<<endl; cout<<setprecision(9)<<fraction<<endl; /*printing numbers 1 to 5 along with their square roots. The square root of every number is printed along with that number as the precision value*/ cout<<"\nnumbers ALONG WITH SQUARE ROOTS\n"; for(i=1;i<=5;i++) cout<<"number IS "<<setprecision(i)<<i<<endl; cout<<"square ROOT OF "<<i<<" IS "<<setprecision(i)<<sqrt(i)<<endl; cout<<"\nusing 'SCIENTIFIC' PRECISION:\n"; cout<<scientific<<pi<<endl; return 1; Output: 22/7 (PI) IS 3.14286 1/3 IS 0.333333 USING SET PRECISION: 5.4 5.375 USING FIXED SET PRECISION: 5.4

C++ Question Bank Page 9 5.37500 5.375000000 NUMBERS ALONG WITH SQUARE ROOTS NUMBER IS 1 SQUARE ROOT OF 1 IS 1.0 NUMBER IS 2 SQUARE ROOT OF 2 IS 1.41 NUMBER IS 3 SQUARE ROOT OF 3 IS 1.732 NUMBER IS 4 SQUARE ROOT OF 4 IS 2.0000 NUMBER IS 5 SQUARE ROOT OF 5 IS 2.23607 USING 'SCIENTIFIC' PRECISION: 3.14286e+000 9. Compare between opening a file with a constructor and opening a file with open( ) method with suitable examples. [1741061] Opening a file using constructor: 1. Create file stream subject to manage the stream using the appropriate class. That is the class ofstream is used to create the output stream and the class ifstream to create the input stream. 2. Initialize the file object with the desired filename. Syntax: ofstream object(file_name); Example: ofstream obj( sample.doc ); This creates obj1 as an ofstream that manages the output stream. #include stream.h #include string.h Void main() char str[]= ssi computer center ; ofstream outfile( sample.doc );

C++ Question Bank Page 10 Opening a file using open(): In order to open a file with a stream object we use its member function open: Syntax: open (filename, mode); where filename is a string representing the name of the file to be opened, and mode is an optional parameter. Example: #include <iostream> #include <fstream> using namespace std; int main () ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0; 10.Describe the various file mode options available in C++ with examples. [1741065] File Modes: The general form of the function open() with two arguments is: stream-object.open ( filename, mode); Parameter Meaning ios::app Append to end of file ios::ate Go to end of file on opening ios::binary Binary file ios::in Open file for reading only ios::nocreate Open fails if the file does not exist ios::noreplace Open fails if the file already exists ios::out Open file for writing only ios::trunc Delete the contents of the file if it exists File pointers and their manipulations.

C++ Question Bank Page 11 Each file has two associated pointers known as the file pointers. They are input pointer and output pointer. The input pointer is used for reading the contents of a given file location and the output pointer is used for writing to a given file location. Read only mode: Input pointer is automatically set at the beginning so that we can read the file from start. Write only mode: Existing contents are deleted and the output pointer is set at the beginning. Append mode: The output pointer is set to the end of file. Functions for manipulations of file pointers: seekg() Moves input pointer to a specified location seekp() Moves output pointer to a specified location tellg() Gives the current position of the input pointer tellp() Gives the current position of the output pointer Example: infile.seekg(10); moves file pointer to the byte number 10. The bytes are numbered from zero hence it points to the 11th byte in the file. ofstream out out.open( filename,ios::app); int p = out.tellp() 11.Describe the various classes available for file operations. [1741064] fstreambase:the base class for ifstream, ofstream, and fstream classes. Functions such are open() and close() are defined in this class. fstream: It allows simultaneous input and output operations on filebuf. This class inherits istream and ostream classes. Member functions of the base classes istream and ostream starts the input and output. ifstream: This class inherits both fstreambase and istream classes. It can access member functions such as get(), getline(), seekg(), tellg(), and read(). It allows input operations and provides open() with the default input mode.

C++ Question Bank Page 12 ofstream: This class inherits both fstreambase and ostream classes. It can access member functions such as put(), seekp(), write(), and tellp(). It allows output operations and provides the open() function with the default output mode. filebuf: The filebuf is used for input and output operations on files. This class inherits streambuf class. It also arranges memory for keeping input data and for sending output. The I/O functions of istream and ostream invoke the filebuf functions to perform the insertion and extraction on the streams. 12.Draw the neat diagram of various classes available for file operations. [1741063]

C++ Question Bank Page 13 13.Describe the following functions for manipulation of file pointers : a) seekg() b) seekp() c) tellg() d) tellp(). [1741062] In C++ we have a get pointer for getting (i.e. reading) data from a file and a put pointer for putting(i.e. writing) data to the file. seekg() is used to move the get pointer to a desired location with respect to a reference point. Syntax: file_pointer.seekg (number of bytes,reference point); Example: fin.seekg(10,ios::beg); seekp() is used to move the put pointer to a desired location with respect to a reference point. Syntax: file_pointer.seekp(number of bytes,reference point); Example: fout.seekp(10,ios::beg); tellg() is used to know where the get pointer is in a file. Syntax: file_pointer.tellg(); Example: int posn = fin.tellg(); tellp() is used to know where the put pointer is in a file. Syntax: file_pointer.tellp(); Example: int posn=fout.tellp(); The reference points are: ios::beg from beginning of file ios::end from end of file ios::cur from current position in the file. In seekg() and seekp() if we put sign in front of number of bytes then we can move backwards.

C++ Question Bank Page 14 14.Detect the end of file condition successfully. Explain. [1741065] C++ provides a special function, eof( ), that returns nonzero (meaning TRUE) when there are no more data to be read from an input filestream, and zero (meaning FALSE) otherwise or fin() can be used that returns 0 on the end of file. End of file in C++ can be detected using eof. While reading data from a file, if the file contains multiple rows, it is necessary to detect the end of file. This can be done using the eof() function of ios class. It returns 0 when there is data to be read and a non-zero value if there is no data. 15.Explain sequential input and output operations (put(), get(), read() and write()). [1741061] put()-the function put () writes a single character to the associated stream. Syntax: obj.put(char ch); Example: fout.put(ch); get()-the function get () reads a single character to the associated stream. Syntax: obj.get(char &ch); Example: fout.put(ch); read()-the read() function is used to read object (sequence of bytes) to the file. Syntax: fin.read( (char *) &obj, sizeof(obj) ); Example: f.read((char*)&stu,sizeof(stu)); write()-the write() function is used to write object or record (sequence of bytes) to the file. Syntax: fout.write( (char *) &obj, sizeof(obj) ); Example: f.write( (char *) &Stu, sizeof(stu) ); 16.Write a C++ program that reads a text file and creates another file that is identical except that every sequence of consecutive blank spaces is replaced by a single space. [1741062]

C++ Question Bank Page 15 #include<fstream> #include<iostream> #include<string.h> #include<conio.h> using namespace std; main() ifstream f1; ofstream f2; char s[10],t[10],ch; strcpy(s,"source.txt"); strcpy(t,"target.txt"); //Creating Source File f2.open(s); f2<<"welcome to File Handling"<<endl; f2.close(); //Checking for mutiple spaces and copying source content to target content f1.open(s); f2.open(t); if(!f1) cout<<"error\n"; exit(0); f1.get(ch); while(!f1.eof()) f2<<ch; cout<<ch; if(ch==' ') while(ch==' ') f1.get(ch); f2<<ch; cout<<ch; f1.get(ch); f1.close();

C++ Question Bank Page 16 f2.close(); //Displaying Source and Target Content system("cls"); cout<<"source File Contents\n"; f1.open(s); while(!f1.eof()) f1.get(ch); cout<<ch; f1.close(); cout<<"\n\ntarget File Contents\n"; f1.open(t); while(!f1.eof()) f1.get(ch); cout<<ch; f1.close(); getch(); Output: Source File Contents Welcome to File Handling Target File Contents Welcome to File Handling