Thowing exceptions for type input

I'm trying to get input from a user, put that input into a string, then check the string to see if it is an integer value. I have been searching all over the C++ reference, looking at stringstream, atoi and typeinfo, but I haven't been able to figure out how to throw an exception if the user inputs "f".

This code doesn't compile, but I think it demonstrates what I want to accomplish:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
  string mystring;
  cout << "Input a number: ";
  cin >> mystring;
  try
  {
    cout << int(mystring) << endl;
  }
  catch (int e)
  {
    cout << "Error " << endl;
  }
  return 0;
}
I've looked over some tutorials on how to convert string to int, but none have showed how to throw an exception if anything other than a number is used. Any advice is much appreciated.
It's simple. Check that all the characters are digits.
http://cplusplus.com/reference/clibrary/cctype/

-Albatross
Excellent, thank you.

1
2
3
4
5
6
7
8
9
10
11
12
bool sisint(string a)
{
  bool cont = true;
  char store[a.length()]; //Store the characters from string
  for (int x = 0; x < a.length(); x += 1)
  {
    store[x] = a[x];
    if (isdigit(store[x]) == false)
      cont = false;
  }
  return cont;
}
char store[a.length()]; //Store the characters from string

This is illegal C++, and is unnecessary anyways. Just use the string like you would a char array.
Topic archived. No new replies allowed.