Catching Errors

When you are learning to program, a typical program is to read in some numbers and do some operations with them.

In practical applications, that is not a good idea. The user may enter a $ or other value that is not numeric. When that happens, the user doesn't know they have made a mistake but may get strange results.

It is much safer to read in a string and convert the string to an integer using stoi (string to int: pronounce as S-to-I). If the conversion fails, we can catch the error and handle it in an appropriate way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
#include<string>
using namespace std;
int main(void) {
  string input;
  int num;
  cout<<"enter a number:";
  cin>>input;
  try { //try to convert string to int
    num=stoi(input); //converts string "12" or "12x" to the integer 12, "2.5" to 2, but "$12" throws error
    cout<<num<<" is a number\n"; //output the valueif conversion worked
  }
  catch(invalid_argument&) { //catch error if string cannot be converted to int    
    cout<<"Cannot convert "<<input<<" to integer\n";
  }
  system("pause");
  return 0;
} //main 
CODE

NEXT: Reading doubles