Read chars strings doubles from a txt file and put them in a class vector in order to use them

So, I have this records.txt file :

c Ann y

c Bob n

t Ann +534.50

t Bob +40.00

t Bob -45.99

I want to take every line from the txt file and store it to a vector of a class that I have to make and print the vector.

How can I do that?

Thanks.

My code without the printing:

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;

class Bank_Acc
{
public:
char action;
string name;
char credit;
int ammount;
private:
Bank_Acc(char a, string b, char c, int d):
action(a), name(b), credit(c), ammount(d){}
};



int main()
{
vector <Bank_Acc> accounts;
Bank_Acc temp;
ifstream infile;
infile.open ("records.txt");

if (!infile)
{
cerr << "Error in opening the file" << endl;
return 1;
}

while (getline(infile, temp))
{
accounts.push_back(temp);
}

}
How can I write it correctly? and what would be the printing format?
Last edited on
A few problems:

Line 10-13: Why are your member variables public? The purpose of a class is to encapsulate an object. Making the variables public means they can be modified from anywhere in your program. Not a good design.

Line 15: Why is your constructor private? That means it can't be called from anywhere.

Line 23: This requires a default constructor, which you do not have.

Line 34: You can't read a struct or class instance like that. That form of getline requires that the second argument is a std::string.

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;

class Bank_Acc
{   char action;
    string name;
    char credit;
    int amount;
public:
    //  Default constructor
    Bank_Acc () 
    {   action = ' ';
        credit = '+';
        amount = 0;
    }        
    Bank_Acc(char a, string b, char c, int d):
    action(a), name(b), credit(c), amount(d){}
    
    //  Read an instance from a stream
    bool Read (istream & is)
    {   return is >> action && is >> name && is >> credit && is >> amount;
    }
};

int main()
{   vector <Bank_Acc> accounts;
    Bank_Acc temp;
    ifstream infile;
    
    infile.open ("records.txt");
    if (!infile)
    {   cerr << "Error in opening the file" << endl;
        return 1; 
    }
    while (temp.Read(infile)) 
    {   accounts.push_back(temp);
    } 
    return 0;
}
Last edited on
Topic archived. No new replies allowed.