0% found this document useful (0 votes)
32 views

C++ 5

The document discusses exceptions in C++ code. It provides an example of C++ code that uses try/catch blocks to handle exceptions. The code prompts the user to enter two numbers and performs a division operation. It uses try/catch blocks to check for invalid input from the user, such as non-numeric characters or a zero denominator, and prints error messages if an exception is thrown.

Uploaded by

Ankur Singh
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

C++ 5

The document discusses exceptions in C++ code. It provides an example of C++ code that uses try/catch blocks to handle exceptions. The code prompts the user to enter two numbers and performs a division operation. It uses try/catch blocks to check for invalid input from the user, such as non-numeric characters or a zero denominator, and prints error messages if an exception is thrown.

Uploaded by

Ankur Singh
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 12

ASSIGHNMENT

NO:5
Ans 1

#include<iostream.h>

#include<conio.h>

Int m[2],a;

Void main()

Cout<<”enter the three marks that you want to enter:”;

Cin>>m[0]>>m[1]>>m[2];

A=m[0]+m[1]+m[2];

Cout<<a;

Try

If(a=0);

Cout<<”error in file”;

Else

Cout<<a;

Getch();

Ans 2

Ans 3
It is only in the most exceptional cases that I want my application to
finish without tidying up after itself. Yes I want this facility but
this is the exception (no pun intended) not the rule.

If I detect an unexpected exception (ie a contract was broken) I may


want the application to finish (trying to avoid the word terminate)
but I would rather unwind the stack and make sure all the destructor's
are called so that all my resources are nicely cleaned up and then
finish the application.

But notice the key word here is (detected). We have detected the
breach in contract so there is a possibility that we could do
something about it, probably not a lot we can do but we don't need to
penalize other applications (ie your DB because the connection is
unexpectedly been severed) because our client has misbehaved.

But we are talking very much in generalities here and each situation
is unique and will require its own ****ysis.
Yes we both agree that the application should terminate (probably as
quickly as possible). I just don't think terminate() is a good idea in
most situations and thus my tendency not to use exception
specifications unless I have a high level of control.
=========================================
#include <iostream.h>
#include <exception.h>

class sys_exception { };

void f ( ) throw (sys_exception)


{
throw std::exception( );
}

int main ( )
{
try
{
f( );
}
catch (sys_exception& se)
{
std::cerr << "System Exception thrown" << std::endl;
}
catch (std::exception& e)
{
std::cerr << "Exception thrown" << std::endl;
}
catch (...)
{
std::cerr << "Unknown Exception thrown" << std::endl;
}

return 0;
}
===================================

Ans 4

By eliminating one of the reasons for if statements.

The commonly used alternative to try / catch / throw is to return a return


code (sometimes called an error code) that the caller explicitly tests via
some conditional statement such as if. For example, printf(), scanf() and
malloc() work this way: the caller is supposed to test the return value to
see if the function succeeded.

Although the return code technique is sometimes the most appropriate


error handling technique, there are some nasty side effects to adding
unnecessary if statements:

• Degrade quality: It is well known that conditional statements are


approximately ten times more likely to contain errors than any other
kind of statement. So all other things being equal, if you can
eliminate conditionals / conditional statements from your code, you
will likely have more robust code.
• Slow down time-to-market: Since conditional statements are
branch points which are related to the number of test cases that are
needed for white-box testing, unnecessary conditional statements
increase the amount of time that needs to be devoted to testing.
Basically if you don't exercise every branch point, there will be
instructions in your code that will never have been executed under
test conditions until they are seen by your users/customers. That's
bad.
• Increase development cost: Bug finding, bug fixing, and testing
are all increased by unnecessary control flow complexity.

So compared to error reporting via return-codes and if, using try / catch /
throw is likely to result in code that has fewer bugs, is less expensive to
develop, and has faster time-to-market. Of course if your organization
doesn't have any experiential knowledge of try / catch / throw, you might
want to use it on a toy project first just to make sure you know what
you're doing — you should always get used to a weapon on the firing
range before you bring it to the front lines of a shooting war.

Ans 5

#include "math.h" // for sqrt() function

using namespace std;

int main()

cout << "Enter a number: ";

double dX;

cin >> dX;

try // Look for exceptions that occur within try block and route to atta
ched catch blck(s)

// If the user entered a negative number, this is an error conditi


on

if (dX < 0.0)

throw "Can not take sqrt of negative number"; // throw exception of


type char

// Otherwise, print the answer

cout << "The sqrt of " << dX << " is " << sqrt(dX) << endl;

catch (char* strException) // catch exceptions of type char*

{
cerr << "Error: " << strException << endl;

In this code, the user is asked to enter a number. If they enter a positive
number, the if statement does not execute, no exception is thrown, and
the square root of the number is printed. Because no exception is thrown
in this case, the code inside the catch block never executes. The result is
something like this:

Enter a number: 9
The sqrt of 9 is 3

If the user enters a negative number, we throw an exception of type


char*. Because we’re within a try block and a matching exception handler
is found, control immediately transfers to the char* exception handler.
The result is:

Enter a number: -4
Error: Can not take sqrt of negative number

By now, you should be getting the basic idea behind exceptions. In the
next lesson, we’ll do quite a few more examples to show how flexible
exceptions are.

Ans 6

#include <iostream>
#include <string>
using namespace std;

int main()
{
char Number1[40], Number2[40];
double Operand1, Operand2, Result;
char Operator;

// Request two numbers from the user


cout << "This program allows you to perform a division
of two numbers\n";
cout << "To proceed, enter two numbers\n";

try {
cout << "First Number: ";
cin >> Number1;
cout << "Operator: ";
cin >> Operator;
cout << "Second Number: ";
cin >> Number2;

// Examine each character of the first operand


// to find out if the user included a non-digit in
the number
for(int i = 0; i < strlen(Number1); i++)
if( (!isdigit(Number1[i])) && (Number1[i] !=
'.') ) // Allow the period
throw Number1;// Send the error as a
string

Operand1 = atof(Number1);

// Do the same for the second number entered


for(int j = 0; j < strlen(Number2); j++)
if( (!isdigit(Number2[j])) && (Number2[j] !=
'.') ) // Allow the period
throw Number2;// Send the error as a
string

Operand2 = atof(Number2);

// Make sure the user typed a valid operator


if(Operator != '+' && Operator != '-' &&
Operator != '*' && Operator != '/')
throw Operator;

// Find out if the denominator is 0


if(Operator == '/')
if(Operand2 == 0)
throw 0;

// Perform an operation based on the user's


choice
switch(Operator)
{
case '+':
Result = Operand1 + Operand2;
break;

case '-':
Result = Operand1 - Operand2;
break;

case '*':
Result = Operand1 * Operand2;
break;
case '/':
Result = Operand1 / Operand2;
break;
}

// Display the result of the operation


cout << "\n" << Operand1 << " " << Operator
<< " "
<< Operand2 << " = " << Result << "\n\n";
}
catch(const int n)
{
cout << "\nBad Operation: Division by " << n
<< " not allowed\n\n";
}
catch(const char n)
{
cout << "\nOperation Error: " << n << " is not
a valid operator\n\n";
}
catch(const char *BadOperand)
{
cout << "\nError: " << BadOperand << " is not
a valid number\n\n";
}

return 0;
}

Ans 7

a.) A local class is declared within a function definition. Declarations in a local class can
only use type names, enumerations, static variables from the enclosing scope, as well as
external variables and functions.

For example:

int x; // global variable


void f() // function definition
{
static int y; // static variable y can be used by
// local class
int x; // auto variable x cannot be used by
// local class
extern int g(); // extern function g can be used by
// local class

class local // local class


{
int g() { return x; } // error, local variable x
// cannot be used by g
int h() { return y; } // valid,static variable y
int k() { return ::x; } // valid, global x
int l() { return g(); } // valid, extern function g
};
}

int main()
{
local* z; // error: the class local is not visible
// ...}

B.) C++ strings allow you to directly initialize, assign, compare, and reassign with the
intuitive operators, as well as printing and reading (e.g., from the user), as shown in
the example below:

string name;
cin >> name;
// read string until the next separator
// (space, tab, newline)

getline (cin, name);


// read a whole line into the string name

if (name == "")
{
cout << "You entered an empty string, "
<< "assigning default\n";
name = "John";
}

C++ strings also provide many string manipulation facilities. The simplest string
manipulation that we commonly use is concatenation, or addition of strings. In C++,
we can use the + operator to concatenate (or "add") two strings, as shown in the
example below:

string result;
string s1 = "hello ";
string s2 = "world";
result = s1 + s2;
// result now contains "hello world"

Notice that neither s1 nor s2 are modified! The operation reads the values and
produces a result corresponding to the concatenated strings, but doesn't modify the
two original strings.

The += operator can also be used. In that case, one string is appended to another
one, as shown in the following example:

string result;
string s1 = "hello";
// without the extra space at the end
string s2 = "world";
result = s1;
result += ' ';
// append a space at the end
result += s2;
Now, result contains the string "hello world".

You can also use two or more + operators to concatenate several (more than 2)
strings. The following example shows how to create a string that contains the full
name from first name and last name (e.g., firsname = "John", lastname = "Smith",
fullname = "Smith, John"):

#include <iostream>
#include <string>
using namespace std;

int main()
{
string firstname, lastname, fullname;

cout << "First name: ";


getline (cin, firstname);
cout << "Last name: ";
getline (cin, lastname);

fullname = lastname + ", " + firstname;


cout << "Fullname: " << fullname << endl;
return 0;
}

c.)

#include <iostream>
#include <ostream>
#include <string>

using namespace std;

template<typename T, typename C>


class ManipInfra
{
public:
ManipInfra(
basic_ostream<C> &(*pFun)(basic_ostream<C> &, T),
T val
): manipFun_(pFun), val_(val)
{
}

void operator()(basic_ostream<C> &os) const


{
manipFun_(os, val_);
}

private:
T val_;
basic_ostream<C> &(*manipFun_)(basic_ostream<C> &, T);
};
template<typename T, typename C>
basic_ostream<C> &operator<<(
basic_ostream<C> &os,
const ManipInfra<T, C> &manip
)
{
manip(os);

return os;
}

ostream &setTheWidth(ostream &os, int n)


{
os.width(n);

return os;
}

ManipInfra<int, char> setWidth(int n)


{
return ManipInfra<int, char>(setTheWidth, n);
}

int main()
{
cout << setWidth(10) << right << "foo" << endl;
}

Ans 8

Memory alllocation for pointer is same as unsigned integer.


bcoz pointer variable stores the address of the variable to which it is pointing to regardless of
its data type.

for eg.

char *charptr;
int *intptr;

here sizeof(charptr) sizeof(intptr)


Ans 9

Ans 10

First, unless you are using a really old version of the C++ library - by which I
mean pre- ANSI / ISO standard C++ - the names of the header file is just fstream
- the standard C++ library headers now have no .h suffix. Note that the C++
standard was published in 1998 so most compilers have had time to catch up to
the standard.

fstream is part of the C++ IOStream library so you may also require certain
other headers as well such as iostream and/or iomanip.

Now I cannot provide you with "the codes" because "the codes" do not exist.
How you wish to use the IOStream library features is up to you and presumably
depends on your application's requirements.

I am going to have to presume that you understand the basics of creating an


application using C++ - editing the code, compiling it, linking it with libraries an
other modules, debugging the executable. I also assume you are familiar with
the concept of including header files to gain declarations and definitions for
items external to the module being compiled - such as file I/O stream facilities.

Sorry but I am not going to be able give you a complete reference - that would
take too long - I suggest you obtain a good standard C++ library reference -
such as "The Standard C++ Library a Tutorial and Reference" by Nicolai M.
Josuttis - which I use all the time. The chapter on IOStreams is 100 pages long -
although this covers more than just the file access aspects of IOStreams.

Now to operate on a file you use std::ifstream objects for reading (input) and an
std::ofstream objects for writing (output). These are the types for char sized
characters. They have equivalents for wide character type (wchar_t) characters -
std::wifstream and std::wofstream. Note that the std:: prefix is used because,
like practically all C++ standard library entities, these types are defined in the
std namespace. I am not going to go into namespaces here, if you do not
understand them then refer to a good, modern, C++ language reference.

Before using a file you must open it - for reading, writing or both. You can create
a new file (useful in this case), or open an existing file (useful for reading and
writing an existing file). A file can be opened either when a file stream object is
created - using one of their constructors - or later by calling an open member
function.

One of the things you wish to do is create a file - so presumably you wish to write
to it in this case. You can do this like so:

#include <fstream>
//...

// In some function:

std::ofstream outFile("myfile.txt" );

if ( ! outFile )
{
// Open failed - take error handling action.
}
This opens the file myfile.txt for writing, creating the file if necessary and
emptying any previous contents. This is the default open mode for std::ofstream.
The default open mode for std::ifstream is open an existing file for reading. This
is the only way std::ostream and std::ifstream differ. Both allow these default to
be overridden by the use of a second parameter to their constructors (or open
member functions):

You might also like