Reading data from a file.

Hello, so I am trying to read data from a file, each line has 7 pieces of information i need to store in different variables. Im not sure how to separate pieces of each line. I could really use some help

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
int main(int argc, const char * argv[]) {

	string baseDir = "C:\\Users\\Brian\\Desktop/";
	Triangle triangles[100];
	int tCount = 0;

	const int BUFFER_SIZE = 128; // 
	char buffer[BUFFER_SIZE];
	string oneTriangleData[10]; // There are 7 data points for each triangle

	ifstream datafile;
	datafile.open(baseDir + "triangles6.csv");
	while (!datafile.eof()) {
		datafile >> buffer;
		cout <<  buffer << endl;
		splitStringByCommas(buffer, oneTriangleData);
		
	
		// Each line in the file is one triangle
		// The lines are encoded like this:
		// x1,y1,x2,y2,x3,y3,color
		// with commas between the data points, and no spaces

	}
	datafile.close();

// This function was provided by the teacher
void splitStringByCommas(string s, string pieces[]) {
	size_t comma = 0;
	int piece = 0;
	while (comma != string::npos) {
		comma = s.find(',');
		pieces[piece++] = s.substr(0, comma);
		s = s.substr(comma + 1);
	}
	pieces[piece] = s; // remainder
}
I'd recommend using getline() to retrieve an entire line from the file. Then use a stringstream to parse that line. Something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
struct Triangle
{
    int x[3];
    int y[3];
    int color;
};
...

std::vector<Triangle> triangles;

istringstream sin;
...
while(getline(datafile, buffer)) // Read an entire line into a buffer.
{
    char comma;
    triangle temp;
    sin.str(buffer); // associate the buffer to the stringstream.
    for(size_t i = 0; i < 3; ++i) // Process the vertexes. 
       sin >> temp.x[i] >> comma >> temp.y[i] >> comma;
    sin >> temp.color;

    triangles.push_back(temp);
}
...
Topic archived. No new replies allowed.