user2420948
user2420948

Reputation: 21

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;
}

Upvotes: 0

Views: 725

Answers (3)

David
David

Reputation: 21

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.

Upvotes: 2

Mahesh
Mahesh

Reputation: 34625

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.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

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);
}

Upvotes: 0

Related Questions