std::cin exception handling
Code:
#include <iostream>
#include <fstream>
#include "MoneyManagement.h"
int main ()
{
std::ifstream iMoney("money.txt");
if(!iMoney){
std::cout<< "Error opening file.\n\n";
}
double a;
iMoney >> a;
while(true){
std::cout << "What would you like to do?\n\n1. Update balance\n2. Print balance\n3. Exit\n\n";
int x;
try{
std::cin >> x;
if(!std::cin){
throw "Error: Please input an integer";
}
}
catch (const std::string& msg){
std::cout << msg << std::endl;
}
MoneyManagement updM;
switch (x) {
case 1:
std::cout << "\nInput new amount:\n";
double upd;
std::cin >> upd;
std::cout << std::endl;
a = upd;
updM.saveData(a);
break;
case 2:
std::cout << "Current balance: " << a << std::endl;
break;
case 3:
return 0;
}
}
}
I'm a complete noob at exception handling and barely understand how to do it properly. The !std::cin idea is something I got while searching online, but for some reason it just won't work in my program. It compiles correctly but if I input a string the program crashes and returns 3. Does anybody know what I'm doing wrong?