Loading from a .csv file

I've done this before but I've gone brain dead / blank arghc!

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
void LoadDataBase( std::vector<DBitem>& db, char* fileName )
{
	FILE* file = fopen(fileName, "r");

	if(file)
	{
		char buffer[1024];
		fgets(buffer, 1024, file);

		while(fgets(buffer, 1024, file))
		{
			DBitem t;
			char* comma = strchr(buffer, ',');
			comma = 0;
			comma++;
			
			t.name = buffer;

			char* comma2 = strchr(comma, ',');
			comma2 = 0;
			comma2++;

			t.directory = comma;

			char* newLine = strchr(comma2, '\n');
			newLine = 0;

			t.number = atoi(comma2);

			db.push_back(t);
		}
	}
}


So the file looks like
1
2
3
4
5
6
NAME,DIRECTORY,NUMBER
bob1,Data\Bob.png,1
bob2,Data\Bob.png,2
bob3,Data\Bob.png,3
bob4,Data\Bob.png,4
bob5,Data\Bob.png,5


Ok so i use fgets to remove the first line. Then grab the next line and want to cut it up into 3 sections. Where the commas are and the newline is. So I can slice up the line into sections and dump it into the structure. It's a simple structure just has:
1
2
3
4
5
6
struct DBitem
{
	std::string name;
	std::string directory;
	int number;
};


Hopefully it kind of makes sense what I'm trying to do as it's a little hard to explain. It compiles fine but crashes right away.

Thanks - If you want me to try to explain and area more in what I'm doing let me know. But i think one of you might see what I'm doing wrong right away.
I'm feeling generous.
1
2
3
4
5
6
7
8
9
/*(getline)*/
size_t first=line.find(','),
    second=line.find(',',first+1);
name=line.substr(0,first);
directory=line.substr(first+1,second-(first+1));
{
    std::stringstream stream(line.substr(second+1));
    stream >>number;
}
Last edited on
Thanks for that helios - but sadly I'm trying to do it using strchr.
Why?
You know when you have your mind set on something, and you want to get it to work a certain way just to put yourself at rest (least thats what I do, I know I'm sad - don't need to point that out :) )
Whatever. Do exactly what I did up there, but change x.find(y,z) to strchr(x+y,z).
Whatever.
If anyone wanted to see the solution :

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
void LoadDataBase( std::vector<DBitem>& db, char* fileName )
{
	FILE* file = fopen(fileName, "r");

	if(file)
	{
		char buffer[1024];
		fgets(buffer, 1024, file);

		while(fgets(buffer, 1024, file))
		{
			DBitem t;
			char* comma = strchr(buffer, ',');
			*comma = 0;
			comma++;
			
			t.name = buffer;

			char* comma2 = strchr(comma, ',');
			*comma2 = 0;
			comma2++;

			t.directory = comma;

			char* newLine = strchr(comma2, '\n');
			*newLine = 0;
			newLine++;

			t.number = atoi(comma2);

			db.push_back(t);
		}
	}
}

I missed the bloody * on the comma, comma2 and newLine lol
Topic archived. No new replies allowed.