A Problem with Vectors

Hi, i have a little problem with vectors in c++.First i will post the code and then explain what happens, and what it should.

1
2
3
4
5
6
7
8
9
10
11
12
13
std::ifstream file(szFilename);
	if(!file)
		THROW_ERROR("Cannot find/open .WOP File!");
	
	std::vector<LPCSTR> vObjectFilename;
	char cObjectFilename[32];

	while(!file.eof())
	{
		file >> cObjectFilename;
		vObjectFilename.push_back(cObjectFilename);
	}
	THROW_ERROR(vObjectFilename.at(0));


Ok, so i want to read some strings from a file and put them in a vector.The file contains 2 strings atm: testmodel.x and tiger.x.The problem is that all vector elements (0 and 1) take the same value: tiger.x instead of the first(0) being testmodel.x and the second(1) tiger.x.In the code above it appears tiger.x instead of testmodel.x(Note that the THROW_ERROR thingy is just my lazy way of debugging the code :P).Another thing, if i move the THROW_ERROR thing inside the while loop it prints testmodel.x as it should.It seems like the next read overwrites the first element or something.

Thanks.
Last edited on
You're just storing the same pointer in the vector over and over.
Use std::string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
std::ifstream file(szFilename);
	if(!file)
		THROW_ERROR("Cannot find/open .WOP File!");
	
	std::vector<LPCSTR> vObjectFilename;
	std::string str;
	//char cObjectFilename[32];

	while(!file.eof())
	{
		file >> str;
		vObjectFilename.push_back(str.c_str());
	}
	THROW_ERROR(vObjectFilename.at(0));

The same thing happens ^
It's
1
2
3
4
5
	std::vector<std::string> vObjectFilename;
	while(file >> str)
	{
		vObjectFilename.push_back(str);
	}
Thanks a lot! It works fine now :D
Topic archived. No new replies allowed.