Professional Documents
Culture Documents
OOPS Unit 3
OOPS Unit 3
UNIT III
SYLLABUS
Exception handling - Streams and formatted I/O – file handling – namespaces – String
Objects - standard template library.
PART – A
1) What are Exceptions?
Exception refers to unexpected condition in a program. The unusual
conditions could be faults, causing an error which in turn causes the program
to fail. The error handling mechanism of C++ is generally referred to as
exception handling.
Syntax:
try
{
………
………
throw exception;
}
catch (type arg)
{ }
Try block
Catch block
exception
Catches all exceptions thrown
from within try block or by
function invoked within a try block
Keyword
try
{
//code raising exception or referring to a function raising exception
}
catch(type_id1)
{
//actions for handling an exception
}
…
…
catch(type_idn)
{
//actions for handling an exception
}
Catch(T)
{
// actions for handling an exception
}
throw T;
10) List out the tasks to be performed for error handling code
1) Detect the problem causing exception (Hit the exception)
2) Inform that an error has occurred (Throw the exception)
3) Receive the error information (Catch the exception)
4) Take corrective actions (Handle the exceptions)
Catch(…)
{
//actions for handling an exception
}
16) What are the functions supported by C++ to handle uncaught exceptions ?
The functions supported by C++ to handle uncaught exceptions are
terminate ( )
set_terminate ( )
unexpected ( )
set_unexpected ( )
17) What are streams?
A Stream is a sequence of bytes. It can either as a source from which the input
data can be obtained or as a destination to which the output data can be sent
The stream source that provides data to the program is called the input stream
and the destination stream that receives output from the program is called output
stream.
18) What are the stream classes for console operations?
a)ios
b)istrean
c)ostream
d)iostream
e)streambuf
19) Draw the console stream classes for hierarchy
ios
iostream
c)fill()
d)setf()
e)unsetf()
27) What are the flags that do not have bit fields?
a)ios::showbase-Use base indicator on output
b)ios::showpos-Print + before positive integers
c)ios::showpoint-Show trailing decimal point and zeros
d)ios::uppercase-Use uppercase letters for hex output
e)ios::unitbuf-Flush all streams after insertion
g)ios::stdio-Flush stdout and stderr after insertion
29) What are the functions that the file stream class provides?
a)seekg()-Moves get pointer to a specified location
b)seekp()-Moves put pointer to a specified location
c)tellg()-Gives the current position of the get pointer
d)tellp()-Gives the current position of the put pointer
The using namespace statement specifies that the members defined in std namespace
will be used frequently throughout the program
namespace namespace_name
{
//Declaration of
//variables,functions,classes,etc.
}
4)Multimap
45) What is meant by Derived Containers?
The derived containers do not support iterators and therefore we cannot
use them for data manipulation. They support two member functions pop() and push()
for implementing deleting and inserting operations.
46) What are the types of derived containers
The STL provides three types of derived containers
1)Stack
2)Queue
3)Priority_queue
47) What is meant by vector?
The vector stores elements in contiguous memory locations and enables direct
access to any element using the subscript operator[].A vector can change its size
dynamically and therefore allocates memory as needed at run time
48) What is meant by lists?
The list is another container that is popularly used. It supports a bidirectional,
linear list and provides an efficient implementation for deletion and insertion
operations.
49) What is meant by maps?
A map is a sequence of pairs where a single value is associated with each
unique key. Retrieval of values is based on the key and is very fast. We should specify
the key to obtain the associated value.
Key1 Value1
Key2
Value2
. .
. .
. .
. .
. .
Key N
.
. ValueN
The source stream provides data to the program called the input stream
and the destination stream that
receives data from the program is called the output stream.
57) Storing programs and data permanently in main memory is not preferred .
Give reasons .
Main memory is usually too small to permanently store all the needed programs
and data.
Main memory is a volatile storage device, which loses its contents when power
is turned off.
PART – B
Exception Handling
Exception handling is a mechanism provided by C++ to handle when an exception
occurs.
Exception Handler
The catch block which is executed when a specific exception is thrown
Exception Specification
A list contained in the ( ) braces after the function header and throw keyword. The
contents of the list are the only valid type of exceptions that can be thrown from
that function.
3. Abnormal Termination
Whenever something goes wrong, we call exit ( ) or abort ( ) function to terminate
the execution of the program, which displays an error message before terminating.
Use of this procedure means, that an error would eventually crash the program.
Try-Block
Try block throw an exception.
Code need to be monitored is placed within the try block
Try block contains either a throw statement or a function containing either a
throw statement or a similar function inside the body.
try
{
//code for raising exception
}
Catch-Block
This is the section where the exception is handled.
Within the try block, by an explicit throw statement or by calling a function
with such a throw statement, exception is said to be thrown.
The exception is handled by the catch section.
The catch section should immediately follow the try block.
catch (type arg)
{
//statements for managing exceptions
}
Throw –Block
This is a mechanism to generate the exception with the keyword throw
The identifier following throw is a name of variable being thrown.
throw (exception);
throw exception;
throw;
3. Explain how catch all exception is done using a suitable C++ program
It is possible to catch all types of exception in a single catch section.
# include <iostream> switch(reply)
# include<conio> {
using namespace std; case 1:
class MyException throw 10;
{ case 2:
int Exnumber; throw „a‟;
string Exmessage; case 3:
throw Error1;
public: }
MyException(int errno, string catch(….)
errmsg) //Catching all exceptions
{ {
ExNumber=errno; cout<<”Anything thrown caught
ExMessage=errmsg; here”;
} }
}
void ShowEx( )
void main( )
{
{
cout<<”Error number
ExGen( );
is”<<Exnumber;
}
cout<<”Exception is”<<
ExMessage;
}
};
void ExGen( )
{
MyException Error1(10,”Error
Testing”);
cout<<”Press 1 for int 2 for char 3
for object”;
int reply;
cin>>reply;
4. Explain how rethrowing is done using a suitable C++ program [Nov/Dec 2009]
To catch the exception in the function N and also to pass it to any other
function, re-throw an exception after catching it.
# include <iostream> //throw exception
# include<conio> case 3:
using namespace std; throw Error1;
class MyException //throw exception }
{ catch(int x){
int Exnumber; throw; //re-throw exception
string Exmessage; }
public: catch(char c) {
MyException(int errno, string errmsg) throw; //re-throw exception
{ }
ExNumber=errno;
catch (MyException my){
throw; //re-throw exception
ExMessage=errmsg;
}
}
}
void ShowEx( )
void main( )
{
{
cout<<”Error number
try {
is”<<Exnumber;
ExGen( );
cout<<”Exception is”<<
}
ExMessage; catch(int)
} {
}; cout<<”integer exception”;
}
catch(char)
void ExGen( ) {
{ cout<<”character exception”<<;
MyException Error1(10,”Error }
Testing”); catch (MyException my)
cout<<”Press 1 for int 2 for char 3 for {
object”; cout<<”Object
int reply; Exception”<<my.show( );
cin>>reply; }
switch(reply) }
{
case 1:
throw 10;
// throw exception
case 2:
throw „a‟;
Example
void ExGen( ) throw(int,char)
{
…………….
}
# include <iostream> catch (MyException my)
# include<conio> {
using namespace std; cout<<”Object Exception”<<my.show(
class MyException );
{ }
int Exnumber; }
string Exmessage;
public: void main( )
MyException(int errno, string errmsg) {
{ try
ExNumber=errno; {
ExMessage=errmsg; ExGen( );
} throw 20;
void ShowEx( ) }
{ catch(int)
cout<<”Error number {
is”<<Exnumber; cout<<”integer exception”;
cout<<”Exception is”<< }
ExMessage; catch(char)
} {
}; cout<<”character exception”<<;
}
void ExGen( ) throw(int,char) catch (MyException my)
{ {
//Terminate.cpp catch(int x)
# include <iostream> {
# include<conio> cout<<”integer exception”<<x;
using namespace std; }
class MyException
{ catch(char c)
int Exnumber; {
string Exmessage; cout<<”character exception”<<c;
public: }
MyException(int errno, string errmsg) catch (MyException my)
{ {
ExNumber=errno; cout<<”Object Exception”<<my.show(
ExMessage=errmsg; );
} }
void ShowEx( ) }
{ void Myterminate( )
cout<<”Error number //own terminate function
is”<<Exnumber; {
cout<<”Exception is”<< ……………………….
ExMessage; //code for file close
} exit(-1);
};
}
void main( )
{
void ExGen( )
void MyTerminate( );
{ set_terminate(My Terminate);
MyException Error1(10,”Error Testing”); ExGen( );
cout<<”Press 1 for int 2 for char 3 for }
object”;
int reply;
cin>>reply;
switch(reply)
{
case 1:
throw 10;
case 2:
throw „a‟;
case 3:
throw Error1;
}
ios
iostream
char c;
cin.get(c); // get a character from keyboard and assign it to c
get(void)
o It returns the input character.
Example:
char c;
c=cin.get();
The value returned by the function get() is assigned to the
variable c.
The function put() a member of ostream class, can be used to output a line
of text, character by character.
Example:
cout.put(„x‟); // displays the character x
cout.put(ch); // displays the value of variable ch
We can also use number as an argument to the function put(). It
converts the number into corresponding character using ASCII value.
PROGRAM:
#include<iostream> Output:
using namespace std; Input
int main() Object Oriented Programming
{ Output
int count=0; Object Oriented Programming
char c; Number of characters=27
cout<<”Input Text”;
cin.get(c);
while(c!=‟\n‟)
{
cout.put(c);
count++;
cin.get(c);
}
cout<<”number of
characters=”<<count<<”\n”;
return 0;
}
The write() function displays an entire line and has the following form:
cout.write(line, size)
o The first argument line represents the name of the string to be
displayed.
o The second argument indicates the number of characters to be
display.
PROGRAM:
#include<iostream> for(i=n;i>0;i--)
using namespace std; {
int main() cout.write(string2,i);
{ cout<<”\n”;
char *string1=”C++”; }
char *string2=”Programming”; cout.write(string1,m).write(string2,n);
int m=strlen(string1); // Concatenating strings
int n=strlen(string2); cout<<”\n”;
for(int i=1;i<n;i++) cout.write(string1,10);
{ // Crossing the boundary
cout.write(string2,i); return 0;
cout<”\n”; }
}
cout.precision(d);
d is the number of digits to the right of the decimal point.
Eg:
cout.precision(3);
cout<<sqrt(2)<<”\n”;
cout<<3.14159<<”\n”;
cout<<2.50032<<”\n”;
The corresponding output will be,
1.141 (truncated)
3.142 (rounded to the nearest cent)
2.5 (no trailing zeros)
Filling and Padding: fill ()
fill() function is used to fill the unused positions by any desired character.
cout.fill(ch);
ch represents the character which is used for filling the unused positions.
Eg:
Cout.fill(„*‟);
Cout.width(10);
Cout<<5250<<”\n”;
The output will be * * * * * * 5 2 5 0
Program:
#include<iostream>
using namespace std;
int main()
{
cout.fill(„<‟);
cout.precision(3);
for(int n=1;n<=6;n++)
{
cout.width(5);
cout<<n;
cout.width(10);
cout<<1.0/float(n)<<”\n”;
if(n==3)
cout.fill(„>‟);
}
cout<<”Padding changed”;
cout.fill(„#‟);
cout.width(15);
cout<<12.345678<<”\n”;
return 0;
}
Output:
<<<<1<<<<<<<<<1
<<<<2<<<<<<<0.5
<<<<3<<<<<0.333
>>>>4>>>>>>0.25
>>>>5>>>>>>>0.2
>>>>6>>>>>0.167
Padding changed
#########12.346
Eg:
Cout.fill(„*‟);
Cout.setf(ios::left, ios::adjustfield);
Cout.width(15);
Cout<<”TABLE 1”<<”\n‟;
Output will be: T A B L E 1 * * * * * * * *
11. What are Manipulators? Explain managing output with manipulators and also
design your own manipulators with example.
Functions which are non-member but provide similar formatting mechanism as
ios functions are called Manipulators.
The header file iomanip provides a set of functions called manipulators which
can be used to manipulate the output formats.
They provide the same features as that of the ios member functions and flags.
output.fill(„*‟);
output.precision(2);
output<<setiosflags(ios::fixed)<<setw(10);
return output;
}
int main()
{
cout<<currency<<form<<7864.5;
return 0;
}
Output: Rs**+7864.50
NAMESPACE
Namespace is used to define the scope that could hold global identifiers.
The best example of namespace scope is the C++ Standard Library.
using namespace std;
It specifies that the members defined in std namespace will be used frequently
throughout the program.
Defining Namespace
The syntax for defining the namespace is as similar to the syntax for defining
class.
namespace namespace_name
{
// Declaration of Variables, Functions, Classes, etc.
}
Eg:
namespace TestSpace
{
int m;
void display(int n)
cout<<n;
}
The variable m and the function display are inside the scope by the TestSpace
namespace. If we want to assign the value for m we mst use the scope resolution
operator,
TestSpace::m=100;
Nesting of Namespace:
A namespace can be nested within another namespace.
Eg:
namespace NS1
{
…………
…………
namespace NS2
{
int m=100;
}
…………
…………
}
To access the variable m,
cout<<NS1::NS2::m;
Or
using namespace NS1;
cout<<NS2::m;
Unnamed Namespaces
An unnamed namespace is one that does not have a name. It occupy global
scope and are accessible in all scopes following the declaration in the file.
PROGRAM:
#include<iostream>
using namespace std;
namespace Name1
{
double x=4.56;
int m=100;
namespace Name2
{
double y=1.23;
}
}
namespace
{
int m=200;
}
int main()
{
cout<<”x=”<<Name1::x<<”\n”;
cout<<”m=”<<Name1::m<<”\n”;
cout<<”y=”<<Name1::Name2::y<<”\n”;
cout<<”m=”<<m<<”\n”;
return 0;
}
Output:
x = 4.56
m = 100
y= 1.23
m =200
1. Sequence Containers
It stores elements in a linear sequence.
Each element is related to other elements by its positions along the line.
Element 0 Element 1 Element 2 Last Element
begin() end()
The STL provides three types of Sequence containers:
vector
o A dynamic array.
o Allows insertions and deletions at back.
o Permits direct access to any element.
list
o A bidirectional linear list.
o Allows insertions and deletions anywhere.
Deque
o A double-ended queue.
o Allows insertions and deletions at both the ends.
o Permits direct access to any element.
2. Associative Containers
It are designed to support direct access to elements using keys.
They are not sequential.
They are of four types,
set
o Used for storing unique sets.
o Allows rapid lookup.
multiset
o Used for storing non-unique sets.
These both containers can store a number of items and provide
operations for manipulating them using the values as the keys.
map
o Used for storing unique key/value pairs.
o Each key is associated with only one value.
o Allows key based lookup.
multimap
o Used ofr storing key/value pairs in which one key may be
associated with more than one values.
o Allows key based lookup.
These both are used to store pairs of items, one called the key and the
other called the value.
3. Derived Containers
The STL provides three derived containers
stack
queue
priority_queue
They are also known as container adapters.
main()
{
vector<string> SS;
int ii;
for(ii=0; ii < SS.size(); ii++)
{
cout << SS[ii] << endl;
}
vector<string>::const_iterator cii;
for(cii=SS.begin(); cii!=SS.end(); cii++)
{
cout << *cii << endl;
}
vector<string>::reverse_iterator rii;
for(rii=SS.rbegin(); rii!=SS.rend(); ++rii)
{
cout << *rii << endl;
}
swap(SS[0], SS[2]);
Output:
Loop by index:
The number is 10
The number is 20
The number is 30
Constant Iterator:
The number is 10
The number is 20
The number is 30
Reverse Iterator:
The number is 30
The number is 20
The number is 10
Sample Output:
3
The number is 30
The number is 10
Examples:
Cin >> s2;
Cout << s2;
Getline (cin,s2);
Example program:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1;
string s2( “new”);
string s3( “delhi”);
s1=s2;
cout<<”s1=”<<s1<<”\n”;
s1=”standard c++”;
cout <<”now s1=”<<s1<<”\n”;
string s4(s1);
cout << “s4=”<<s4<<”\n\n”;
cout <<”ENTER A STRING \n”;
cin>>s4;
cout <<now s4=”<< s4<<”\n\n”;
s1=s2+s3;
cout<< “s1 finally contains: “<<s1 <<‟\n”;
return 0;
}
Output:
S1 = new
Now s1 = standard C++
S4 = standard C++
Enter a string
Computer centre
Now s4 =computer
S1 finally contains: New Delhi
Output:
Original strings are:
S1: 12345
S2: abcde
Place s2 inside s1
Modified s1: 1234abcde5
Remove 5 characters from s1
Now s1: 12345
Replace middle 3 characters in s2 with s1
Now s2: a12345e
Output:
S1 is not equal to s2
S2 greater than s1
S3 is equal to s1+s2
S1<s2
String Characteristics
Class string support many functions that could be used to obtain the
characteristics of string such as,
Example program:
#include<iostream>
#include<string>
using namespace std;
void display(string, &str)
{
cout << “size =”<<str.size() << “\n”;
cout <<”length = “<<str.length() << “\n”;
cout << “capacity =” << str.capacity() << “\n”;
cout << “maximum size = “<< str.max_size() << “\n”;
cout << “empty =”<< str.empty() ? “yes” : “no”);
cout << “\n\n”;
}
int main()
{
string str1;
cout << “initial status: \n”;
display (str1);
cout << “enter a string (one word) \n”;
cin>> str1;
cout <<”status now: \n”
display(str1);
str1.resize (15);
cout<<”status after resizing: \n”;
display(str1);
cout<< “\n”;
return 0;
}
Output:
Initial status:
Size = 0
Length = 0
Capacity = 0
Maximum size = 4294967293
Empty: yes
Enter a string (one word)
India
Status now:
Size = 5
Length =5
Capacity = 31
Maximum size = 4294967293
Empty: no
Status after resizing:
Size = 15
Length =15
Capacity =31
Maximum size = 4294967293
Empty: no
Example program:
#include<iostream>
#include<string>
Using namespace std;
Int main()
{
String s(“ONE TWO THREE FOUR”);
Cout << “the string contains:\n”;
Output:
The string contains:
ONE TWO THREE FOUR
String is shown again:
ONE TWO THREE FOUR
TWO is found at :4
T is found first at : 4
R is found last at : 17
Retrieve and print substring TWO
TWO
Example program:
#include<iostream>
#include<string>
using namespace std;
int main()
string s1 (“road”);
string s2 (“read”);
string s3 (“red”);
cout<< “s1 = “<<s1<< “\n”;
cout<< “s2 = “<<s2<< “\n”;
cout<< “s3 = “<<s3<< “\n”;
int x = s1.compare(s2);
if(x==0)
cout<< “s1 == s2” << “\n”;
else if(x>0)
cout << “s1 > s2” << “\n”;
else
cout<< “s1 < s2” <<”\n”;
int a = s1.compare (0,2,s2,0,2);
int b = s2.compare (0,2,s1,0,2);
int c = s2.compare (0,2,s3,0,2);
int d = s2.compare (s2.size()-1,1,s3,s3.size()-1,1);
cout<<”a =” << a << “\n” << “b = “<< b << “\n”;
cout<<”c =” << c << “\n” << “d = “<< d << “\n”;
cout<<”\n befoe swap: \n”;
cout<< “s1 = “ << s1 << “\n”;
After swap:
s1 = read
s2 = road
The data is stored in these devices using the concept of files. A file is a
collection of related data stored in a particular area on the disk.
Programs can be designed to perform the read and write operations on these
files.
It uses file streams as an interface between the programs and the files.
The stream that supplies data to the program is known as input stream and the
one that receives data from the program is known as output stream.
In other words, the input stream extracts or reads data from the file and the
output stream inserts or writes data to the file.
These classes, designed to manage the disk files, are declared in fstream.h and
therefore we must include this file in any program that uses files.
fstreambase
Provides operations common to the file streams. Serves as a base for fstream, ifstream
and ofstream classes. Contains open() and close() functions.
ifstream
Provides input operations. Contains open() with default input mode. Inherits the
functions get(), getline(), read(), seekg() and tellg() functions from istream.
ofstream
Provides output operations. Contains open() with default output mode. Inherits
put(), seekp(), tellp(), and write() functions from ostream.
fstream
The ifstream, ofstream and fstream classes are declared in the file fstream.h
The istream and ostream classes are also included in the fstream.h file.
A filestream can be defined using the classes ifstream, ofstream, and fstream
that are contained in the header file fstream.h
2. Using the member function open() of the class. This method is used when we
want to manage multiple files using one stream.
Using Constructor
Create a file stream object 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.
ofstream outfile(“sample.txt”);
The above statement creates an object outfile of class ofstream that manages the
output stream. This statement also opens the file sample.txt and attaches it to the
output stream for writing.
ifstream infile(“sample.txt”);
# include
void main()
{
ofstream outfile(“sample.txt”); // create file for output
char ch = „a‟;
int i = 12;
float f = 4356.15;
char arr[ ] = “hello”;
outfile << ch << endl <<<="" endl="" f="" arr;="" send="" the="" data="" to="" file
outfile.close();
ifstream infile(“sample.txt”);
infile >> ch >> i >> f >> arr; // read data from file
#include
#include
void main()
{
char str[]=“C++ is superset of C. It is an object-oriented /
programming language.”;
26. How will you read and write objects of classes in a File.
Writing and reading Objects of a class :
So far we have done I/O of basic data types. Since the class objects are the
central elements of C++ programming, it is quite natural that the language supports
features for writing and reading from the disk files objects directly.
The binary input and output functions read() and write() are designed to do
exactly this job.
The write() function is used to write the object of a class into the specified file
and read() function is used to read the object of the class from the file.
The address of the object must be cast to the type pointer to char.
One important point to remember is that only data members are written to the disk
file and the member functions are not.
#include
class Person
{
private:
char name[40];
int age;
public:
void getData()
{
cout << “\n Enter name:”; cin >> name;
cout << “\n Enter age:”; cin >> age;
}
} ; // End of the class definition
void main()
{
In the open() function we include several mode bits to specify certain aspects of the file
object.
app -> To preserve whatever was in the file before. Whatever we write to the file will be
appended to the existing contents.
We use in and out because we want to perform both input and output on the file.
infile.seekg(10);
Moves the file pointer to the byte number 10.
Thus, the pointer will be pointing to the 11th byte in the file.
Parameter Meaning
ios::app Append to end of the file
ios::ate Go to end of the file on opening
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 contents of the file if it exists
26. Write a C++ program to demonstrate file handling as follows: get strings as
input from the user, store them in a file, retrieves them and displays them.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void menu(void);
void writeData(void);
void readData(void);
string * split(string, char);
const char FileName[] = "c://TestAddress/TestAddress.txt";
ifstream myAddress(FileName);
string name = " ";
string address = " ";
string street= " ";
string city = " ";
string state = " ";
string zipCode = " ";
int record = 0;
ofstream outMyAddress(FileName, ios::out);
int main ()
{
menu();
return 0;
} //end main
void menu(void)
{
//allow user to choose to append records, display records or exit the program
char userChoice = ' ';
//Display Menu
system("cls");
cout << "\nName and Address database:" << endl;
cout << endl;
cout << "\n\n(A)ppend record, (S)how Record, (E)xit:";
cin >> userChoice;
//Users Choice
switch (userChoice)
{
case 'a':
case 'A'://Append Record
myAddress.open (FileName, ios::app);
if (myAddress.is_open())
{
writeData();
}
break;
case 's':
case 'S'://Show record
myAddress.open (FileName, ios:: in);
if (myAddress.is_open())
{
readData();
}
break;
case 'e':
case 'E'://Exit
myAddress.close();
break;
default:
cout << "Invalid choice" << endl;
cout << endl << endl << endl;
break;
}
return;
}//end menu
void writeData(void) //Write the Address Info to a file
{
char answer = ' ';
char response = ' ';
if(myAddress.is_open())
{
//entering loop
while (answer != 'n' || answer != 'N')
{
cout << endl;
getline(cin, name);
cout << "\nEnter name: ";
getline(cin, name);
cout << "\nEnter Street: ";
getline(cin, street);
cout << "\nEnter City: ";
getline(cin, city);
cout << "\nEnter State: ";
getline(cin, state);
cout << "\nEnter Zip Code: ";
getline(cin, zipCode);
cout << endl;
outMyAddress << name << ", " << street << " ," << city << ", " << state << " ," <<
zipCode << endl;
record++;
cout << "\nWould you like to enter another record? (Y/N)" << endl;
cin >> response;
if (response == 'n' || response == 'N')
{
return menu();
}
}
}
myAddress.close();
void readData(void)
{
ifstream inMyAddress(FileName, ios::in);
if(myAddress.is_open())
{
string firstLine;
inMyAddress >> firstLine;
getline (myAddress, firstLine, '\n');
cout << endl;
cout << "Reading the file(s)..." << endl;
cout << endl;
cout << "Record #: " << record << endl;
string *theField = split(firstLine, ',');
cout << "Name......" << theField[0] << endl;
cout << "Street......" << theField[1] << endl;
cout << "City......" << theField[2] << endl;
cout << "State......" << theField[3] << endl;
cout << "Zip Code......" << theField[4] << endl;
}
inMyAddress.close();
system("pause");
return menu();
}
string * split(string theLine, char theDeliminator){
int splitCount = 0;
for(int i = 0; i < ((int)theLine.size()); i++){
if (theLine[i] == theDeliminator)
splitCount++;
return 0;
}
splitCount++;
string* theFieldArray;
theFieldArray = new string[splitCount];
string theField = "";
int commaCount = 0;
University Questions
PART – A
2. What is the purpose of the STL (Standard Template Library)? (Nov/Dec 2010)
Refer Q.No:36
PART – B
4. Write a program that contains a possible exception. Use a try block and throw
it and a catch block to handle it properly. (6)
(Nov/Dec 2011) Refer Q.No:3
5. Write a program that reads a name from the keyboard into three separate
string objects and then concatenates them into a new string object using „+‟
operator and append() function. (10)
(Nov/Dec 2011)
Refer Q.No:19
6. List the major categories of containers supported by STL. (6) (Nov/Dec 2011)
Refer Q.No:13