Save information from afile to an array of objects

Im not sure how to send the information from a file to an array of objects, this is what I have so far

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void displayAll(Houselist house[], int num)
{
	ifstream readfile;
	readfile.open("houseinfo.txt");
	int insert;
	while(!readfile.eof())
	{
		for(int i = 0;i<num;i++)
		{
			readfile >> insert;
			house[i].setNumber(insert);
			
		}
	}

	
}


1
2
3
4
5
6
7
        unsigned i = 0;
	while(!readfile.eof())
	{
			readfile >> insert;
			house[i++].setNumber(insert);
                        if(i >= num) break;
	}

Last edited on
what is the difference between this and the code I had? from what I see they should do the same thing but when I test my code and try to display the contents of the array it doesnt display anything, only spaces, and i get into an endless loop, your code displays the right amount of times but not what I have in the file, it displays what I have in the default constructor
Ever heard of error checking?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void displayAll(Houselist house[], int num)
{
    char const* fname = "houseinfo.txt" ;
    std::ifstream readfile(fname) ;

    if ( !readfile.is_open() )
    {
        std::cerr << "Unable to open file " << fname << '\n' ;
        return ;
    }

    int num ;
    int i = 0 ;

    while ( i < num && readfile >> num )
        house[i++].setNumber(num) ;	

    if ( i < num )
        std::cerr << "Unable to read " << num << " values from " << fname << '\n' ;
}

Topic archived. No new replies allowed.