Catching Errors

In this example we use stod (string to double: pronounce S-to-D) to convert the input to a double.

As you can see, check for an catching errors makes the program much longer.

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;
  double num;
  cout<<"enter a number:";
  cin>>input;
  try { //try to convert string to int
    num=stod(input); //converts string "12.5" or "12.5x" to the double 12.5, but "$12.25" throws error
    cout<<num<<" is a number\n"; //output the value if conversion worked
  }
  catch(invalid_argument&) { //catch error if it cannot be converted to int    
    cout<<"Cannot convert "<<input<<" to double\n";
  }
  system("pause");
  return 0;
} //main 
CODE

NEXT: Finding a total