#include <iostream>
#include <cctype>
usingnamespace std;
int square(int x)
{
if(!isdigit(x))
{
throw" data type mismatch";
}
elsereturn x*x;}
int main()
{
cout << "Enter a number: ";
int x;
cin >> x;
int y;
try
{
y = square(x);
}
catch(std::string str)
{
cout << "Error: " << str;
cin.get();
cin.get();
return 0;
}
catch(...)
{
cout << y << " is " << x << " squared.";}
cin.get();
cin.get();
return 0;
}
First, The exception doesn't do the right thing, as in:
Enter a number: y
(program exits)
,where it should handle the exception.
Secondly and unrelated to exceptions (I believe, at least), the square function returns the incorrect value when a number is inputted. Any ideas?
You cannot use isdigit() on integral values (a number can't be anything but a number). By attempting to assign a char * to an int, you give the int an unpredictable value. Then you pass the int to isdigit(), converting it to a pointer. It's impossible to know what it's pointing to or even whether it's a valid address, so you probably triggered a segmentation fault by just attempting to access that location. If you didn't, isdigit() continues to read the char array until it finds a non-digit character or a zero, so that is likely to cause a segmentation fault eventually, anyway.