Function that reads .txt into a struct

Okay, so for my CS15 class I need to write a function that reads the data from a .txt file into a struct.

I'm close, but I keep getting just a couple errors.

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
44
45
46
47
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>

using namespace std;

// Here is my struct layout:

struct Diamond {
    string stockNumber;
    string cut;
    char color;
    string clarity;
    double carats;
    double cost;
    };

int loadFile(Diamond diamondData[]) { // error: too few arguments to function ‘int loadFile(Diamond*)’

	int totalData = 0;

	ifstream inFile;

	string fileName;
	cout << "Enter filename: ";
	cin >> fileName;

	inFile.open(fileName.c_str());

	do {
		inFile >> diamondData[totalData].stockNumber >> diamondData[totalData].cut >> diamondData[totalData].color >> diamondData[totalData].clarity >> diamondData[totalData].carats >> diamondData[totalData].cost;
        totalData++;
    } while (!inFile.eof());

    inFile.close();

    cout << totalData << " were loaded.";

	return (totalData - 1);
}

int main() {

// Want to call loadFile() here
loadFile(); // error: at this point in file
}


Basically, I need to read the .txt file data into a struct that can be accessed by main() and also 2 other functions.

Can anyone help me? I'd really appreciate it
Last edited on
Can you tell us what the errors are that you are getting?

Also I would consider doing your main loop differently. At the moment you will add a record to your array even if the read fails or reaches the end of file. I would consider something like this:
1
2
3
4
5
6
7
8
9
inFile.open(fileName.c_str());

Diamond d; // input value
while(inFile >> d.stockNumber >> d.cut >> d.color >> d.clarity >> d.carats >> d.cost)
{
    // now we know that the read was a success so we can safely add our data
    diamondData[totalData] = d;
    ++totalData;
}


Also I am concerned that there is no bounds checking on your array. I would seriously consider using a std::vector instead:

http://www.cplusplus.com/reference/stl/vector/
Last edited on
@ Galik

I added the errors above.

As for your suggestions, I will certainly look into them.
Your function loadFile() is expecting you to pass in an array of type Diamond, but you don't pass it anything at all.
Topic archived. No new replies allowed.