为什么我的try catch异常在catch之后停止工作?

问题描述

在这里有一段代码,部分运行。我最初可以输入字符(c,a,r)和数字,但是输入字符输入后,代码不再接受整数输入。为什么会这样?

我认为这与我的try catch异常有关。

代码

#include <iostream>
#include <vector>
#include <string>
#include <iomanip>

using namespace std;

int item;
string input;
float total = 0;
int flag = 0;
float maintotal = 0;

int main() {

  cout.precision(2);
  cout << std::fixed;

  cout << "vending Machine" << endl;
  cout << "----Items------" << endl;

  vendingMachine();
  cout << "Enter c to checkout" << endl;
  cout << "Enter a to add items" << endl;
  cout << "Enter r to remove items" << endl;

  while (true) {
  
    cout << "Enter your selection: " << flush;
    cin >> input;

    try
    {
      item = stoi(input); //convert to int
    }
    catch (exception &e)
    {
        //std::cout << e.what(); 
        flag = -1; //if not set flag
        if (input == "c"){
          checkout();
          
        }
        if (input == "a") {
          add();
          cout << "mainadd total: " << total << endl;
        }
        if (input == "r") {
          remove();
        }

    }

    if (flag != -1) //only execute with no errors
    {
        total = enterSelection();
        
        cout << "total from main: " << total << endl;
    }
  }


  return 0;
}

解决方法

一旦将标志设置为-1,它就永远不会变回0。在文件顶部执行的初始化仅发生一次,甚至在调用main之前。因此,在那之后,当您在catch块中将其设置为-1时,它永远不会进入将其设置回0的代码的一部分。如您所见,在while循环开始时设置flag = 0可以纠正该问题。遗漏。