C++: Vectors of structs and passing them - Error:

2019-08-27 04:38发布

The following program should create a vector of structs and pass that to two functions. I'm honestly getting confused following all the different ways this vector of structs can be passed and what the notation would look like for doing so. Either way, I've come up with this program that compiles but gives me errors when running nonetheless. Specifically, as soon as I input the income amount (first cin in the function).

const int SIZE = 2;

// structure of floats named TaxPayer
struct TaxPayer
{
    float taxRate;
    float income;
    float taxes;
};

// prototypes for taxTaker and taxPrint functions
void taxTaker(vector<TaxPayer>&);
void taxPrint(vector<TaxPayer>&);

int main()
{
    // driver
    // vector of type TaxPayer named "citizen"
    std::vector<TaxPayer>citizen(SIZE);
    taxTaker(citizen);
    taxPrint(citizen);

    return 0;
}

One of the functions in question:

void taxTaker(vector<TaxPayer> &citizen)
{
    int loops = 1;
    bool loopFlag = true;

    // asks for an validates inputs depending on vector size (it's 2 in this     
       case so it asks for inputs from 2 different people)
    do
    {
        cout << "Enter this year's income for tax payer #" << loops << ": " << endl;

        // validates entered income
        do
        {
            cin >> citizen[loops].income;
            if (std::cin.fail() || citizen[loops].income <= 0)
            {
                std::cout << "\nInvalid income. Amount must be over 0" << std::endl;
                std::cin.clear();
                std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
            }
            else
            {
                loopFlag = false;
            }
        }
        while (loopFlag);

        cout << "Enter the tax rate for tax payer #" << loops << ": " << endl;

        // validates entered tax rate
        do
        {
            cin >> citizen[loops].taxRate;
            if (std::cin.fail() || citizen[loops].taxRate < 0.01 || citizen[loops].taxRate > 9.9)
            {
                std::cout << "\nInvalid tax rate. Amount must be over 0.01 and under 9.9" << std::endl;
                std::cin.clear();
                std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
            }
            else
            {
                loopFlag = false;
            }
        }
        while (loopFlag);

        // should calculate the final tax for each person
        citizen[loops].taxes = citizen[loops].income * citizen[loops].taxRate;
        loops++;
    }
    while (loops <= SIZE);

    }

0条回答
登录 后发表回答