Archived

This topic is now archived and is closed to further replies.

tstrimp

STL problems

Recommended Posts

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]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites