Catching Errors

In this example, the user can enter either a number or "Q" to end. If the input is not "Q" and is not an integer, an error messages is printed to let the user know the input was not valid. The invalid input is not added to the total.

output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
#include<string>
using namespace std;
int main(void) {
  string input;
  int num,total=0;
  bool more=true;
  while(more) {
    cout<<"Enter a number or Q to end:";
    cin>>input;
    try { //try to convert string to int
      num=stoi(input); //converts string "12" or "12x" to the integer 12, but "$12" throws error
      total+=num; //add the value to total if conversion worked
    }
    catch(invalid_argument&) { //catch error if string cannot be converted to int
      if(input!="Q" && input!="q") cout<<"Cannot convert "<<input<<" to integer\n";
      else more=false;
    } //catch error
  }//while
  cout<<"Total="<<total<<endl;
  system("pause");
  return 0;
} //main 
CODE

NEXT: Input a date as mm/dd/year