简体   繁体   中英

Reading input into Vector Objects

Hi I am attempting to read data into a vector of objects but I am having trouble doing so. I have created a class and a vector of that class. When I try to read data into the the vector I get class Bank Statements has no member and then the variables i attempt to read in.

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

using namespace std;

class Bank_Statement
{
public:
    Bank_Statement();
    Bank_Statement(int d, double bal, string desc);

private:
    string description;
    double balance;
    int day;
};

Bank_Statement::Bank_Statement(int d, double bal,  string desc)
{
    description = desc;
    balance = bal;
    day = d
}

int main(){
    Bank_Statement statement1;

    cin >> statement1.d >> statement1.bal >> statement1.desc;

    vector<Bank_Statement> user_statements;

    int day_of_month;

    for (day_of_month = 0, day_of_month < user_statements.size(); day_of_month++){
        user_statements.push_back(statement1);
    }

    return 0;
}

The argument names of the constructor are not data members of the class. When you did:

cin >> statement1.d >> statement1.bal >> statement1.desc;

That is not right because those aren't members declared in the class. Use description , balance , and day respectively instead.

It doesn't even enter the loop. When the vector is created, its size is zero. This means that the expression day_of_month < user_statements.size() (the loop condition) will always be false.

You should read the input in the loop, something like

Bank_Statement statement;
std::vector<Bank_Statement> user_statements;

while (std::cin >> statement.d >> statement.bal >> statement.desc)
{
    user_statements.push_back(statement);
}

Thats because of the condition day_of_month < user_statements.size() . Initially vector is empty and does not satisfy the condition to do a push_back operation on the vector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM