-
Exception handling
hi
please can you help me in the following question?
Write a C++ program that inputs a list of integer values in the range of -100 to 100 from the keyboard and computes the sum of the squares of the input values. This program must use exception handling to ensure that the input values are in range and are legal integers, to handle the error of the sum of the squares becoming larger than a standard int variable can store, and to detect end-of-file and use it to cause output of the result. In the case of overflow of the sum, an error message must be printed and the program terminated.
can you please give me a hint how to solve this question?
-
> can you please give me a hint how to solve this question?
Start with a board search for "exception" to see how other people have used it
Which bit of the problem is actually causing you a problem, because at the moment, it's just homework dumped on the board.
-
This was my solution
but i don't know how can i detect an overflow??
Code:
#include <iostream.h>
int main(){
int x;
int eof = 0;
int sum = 0;
cout<<"Enter a list of integers in the range of -100 to 100 (0 to end):"<<endl;
cin>>x;
try{
if(x<-100 || x>100)
throw x;
sum = x*x;}
catch(int e){
cout<<e<<" is out of range"<<endl;}
while(x != eof){
cin>>x;
try{
if(x<-100 || x>100)
throw x;
sum = sum+(x*x);}
catch(int e){
cout<<e<<" is out of range"<<endl;}
}
cout<<"sum of the input squares = "<<sum<<endl;
return 0;}
-
> but i don't know how can i detect an overflow??
One way is like this
Code:
if ( INT_MAX - sum < x ) {
// sum + x will be > INT_MAX - overflow will happen if you try it
// throw exception
}
-