Skip to main content
gamedev.net
🔒 Locked

STL problems

Started by tstrimp Apr 29, 2003 at 8:54 PM 4 replies 500+ views
Original Post
tstrimp
tstrimp
I'm using a STL vector to store (unfortunately) a char array. For some reason when I .push_back() an item to my vector it overwrites my other vector items! main.cpp
    
#include <fstream>

#include <iostream>

#include <vector>

using namespace std;


int main(int argc, char *argv[])
{
	fstream			File;
	char			Temp[255];
	vector<char*>	Data;


	File.open("application.cfg", ios::in);
	while (!File.eof())
	{
		File.getline(Temp, 100);
		Data.push_back(Temp);
	}


	unsigned int i;
	for (i = 0; i < Data.size(); i++)
	{
		cout << Data[i] << endl;
	}


	return 0;
}
  
application.cfg
  
windowwidth	640
windowheight	480
bpp		32
fullscreen	0
  
The output I get from this example is
  
fullscreen	0
fullscreen	0
fullscreen	0
fullscreen	0
  
Any idea what I'm doing wrong?
     Hope is the first step on the road to disappointment [edited by - tstrimp on April 29, 2003 9:56:25 PM]
Sneftel
Sneftel
Keep in mind that if you make a container of pointers, it holds pointers, not the memory they point to. You keep storing the same pointer to the same character array into your vector.

Instead of doing this, either:

a. Instead of having an array, have a pointer, and allocate a new character array to it each time through the loop, or
b. Store std::strings instead, which don''t have to be allocated with new.


How appropriate. You fight like a cow.
tstrimp
tstrimp
I would like to use std::strings instead, that was what I first tried, but fstream.getline() doesn't like strings.

Also if the pointer is pointing to the same place then shouldn't it be repeating the first line of the text file and not the last?

[edited by - tstrimp on April 29, 2003 10:12:34 PM]
risingdragon3
risingdragon3
You can try getline(stream_object,string_object) which should work just fine.
tstrimp
tstrimp
quote:
Original post by risingdragon3
You can try getline(stream_object,string_object) which should work just fine.


The source I was using says nothing about getline being overloaded, what stream_object would I be using? I thought that getline was a member funtion of my stream_object? Or am I getting everything mixed up now?



     Hope is the first step on the road to disappointment
tstrimp
tstrimp
I was clearly getting mixed up but now I get it! I got it to work Thanks for the help guys!



     Hope is the first step on the road to disappointment

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.