Fun (pshht) with exceptions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <cctype>
using namespace std;

int square(int x)
{
    if(!isdigit(x))
    {
        throw " data type mismatch";
    }
    else
return 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?
Last edited on
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.
Last edited on
Topic archived. No new replies allowed.