Search code examples
c++arraysclasspointersfstream

Reading values from a file and using classes


Hi I'm having trouble with filling the values of 2 private class members from an input file which is called money.txt . Can you please tell me why it only reads the first value of the file (after the size which is declared on the first line) and then doesn't read the rest of the values? If my method isn't the best approach can you recommend another method to solve this ?

Here is the money.h file:

#ifndef money_h
#define money_h
class Money{
public:
    void getdollars();
    void getcents();
    void printdollars();
    void printcents();
private:
    int dollars[3];
    int cents[3];
};
#endif

Here's the implementation.cpp

#include"money.h"
#include<fstream>
#include<iostream>
using namespace std;
    ifstream instream;
void Money::getdollars()
{
    instream.open("money.txt");
    int s;
    instream>>s;
    instream>>dollars[0];
    instream>>dollars[1];
    instream>>dollars[2];
}
void Money:: getcents()
{
    instream.open("money.txt");
    int s;  
    instream>>s;
    instream>>cents[0];
    instream>>cents[1];
    instream>>cents[2];
}
void Money:: printdollars()
{
    cout<<*dollars;
}
void Money:: printcents()
{
    cout<<*cents;
}

Here are the main.cpp and money.txt files

#include"money.h"
#include<iostream>
#include<fstream>
using namespace std;

Money** readMoney(Money** &x , char* filename)
{
    int size;
    ifstream instream;
    instream.open(filename);
    instream>>size;
    x = new Money*[size];
    for(int i = 0;i<size;i++)
    {
        x[i] = new Money[size];
        for(int j = 0;j<size;j++)
        {
        x[i][j].getdollars();
        x[i][j].getcents();
        }
    }
    return x;

}
void printmoney(Money **a,int size)
{
    ifstream instream;
    int i = 0 , j = 0;
    while(i<size && j<size)
    {
    a[i][j].printdollars();
    cout<<" ";
    a[i][j].printcents();
    cout<<endl;
    j++;
    }
}
void main()
{
    Money** test;
    ifstream instream;
    readMoney(test,"money.txt");
    printmoney(test,3);
}

Money.txt

3
5 60
2 30
3 21

Solution

  • From a quick look it seems that the code opens the file "money.txt" three times. The first time in the function readMoney, the second time in getdollars and the third time in getcents. Probably this the problem. Open the file only once in readMoney function and pass the opened stream to the instance of Money.