Array of Struct

I have to write a program where it takes in data of name, id, rate, and hours. I have to use an array of struct or this. I am unclear on how I should use ifstream to store the array of struct. Please help, I'm new to this. This is what I was trying to do so far. There is more to this program but I just need some guidance on this part. It is not done as I cant figure it out. THanks

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
  #include <iostream>
  #include <fstream>
  #include <string>
  using namespace std;

  struct Payroll
  {
	string employeeName;
	double employeeID;
	int rate;
	int hours;
  };

  void read_txt_file();


  int main()
  {
	int N=5; // declare a constant
	Payroll empl[n]; //struct array for employee
	
	read_txt_file ();
	

	
	



	return 0;
  }


  void read_txt_file ()
  {
    ifstream myFile;
    myFile.open("Project3.txt");
    

  }
Last edited on
Tried playing around more with the read_txt_file function but I cant get it to output anything. THe program runs but does not output anything

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    ifstream myFile;
    myFile.open("Project3.txt");
    
    
    struct Payroll empl[5];


    for(int i = 0; i < 5; i++)
	{ 
    	myFile >>  empl[i].employeeName;
        myFile >> empl[i].employeeID;
        myFile >> empl[i].rate;
        myFile >> empl[i].hours;
        
	}
Last edited on
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
43
#include <iostream>
#include <string>
#include <fstream>

struct P
{
    std::string employeeName;
    double employeeID;
    double rate;
    double hours; // Think about it, wouldn't it be more logical if employees can work half hours or something?
                  // A data type that can store decimals is better.
};

bool read_txt_file(P p[], const int arraySize)
{
    std::ifstream myFile("Project3.txt");
    if(!myFile)
    {
        std::cerr << "Error: Unable to open file.\n";
        return false;
    }
    else
    {
        while(!myFile.eof())
        {
            // what can you do here if the end of file hasn't been reached?
            // (hint: you're going to be reading value from the file here)
        }
        
    }
}

int main()
{
    const int arraySize = 5;
    P p[arraySize];
    if(read_txt_file(p, arraySize))
	{
		std::cout << "Function returned true" << std::endl;
	}
    return 0;
}
Last edited on
Topic archived. No new replies allowed.