Resizing a Dynamic Memory Array

I've finally told myself that I'm going to learn C++, so I've been using the tutorials on the site, and they're great. I've run into just one problem that I can't seem to find an answer for:

If I create an array using dynamic memory:
1
2
string * line;
line = new string [1];


How can I extend the size of the array while keeping the contents I store in line[0]?

Specifically, my code is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	int x = 0;
	string * line;
	
	ifstream file(FILENAME);
	if(file.is_open())
	{
		while(!file.eof())
		{
			line = new string [++x];
			getline(file, line[x-1]);
		}
		file.close();
		for(int a=0;a<x;a++)
		{
			cout << line[a] << endl;
		}
	}                                                                 

I want to be able to keep resizing the array to be just as large as I need. I'm aware that I could get the size of the file before reading in the lines. I'm just picky and want to know how to do it this way.

Thanks!
Last edited on
Use an STL container such as vector<> or deque<> instead. (Ultimately these classes do exactly what you are asking anyway; they just keep you from having to worry about the details).

Thanks for the quick reply! Wow, the vector<> container is pwn. Here is my code now:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main()
{
	vector<string> line;
	string tmp;

	ifstream file(FILENAME);
	if(file.is_open())
	{
		while(!file.eof())
		{
			getline(file, tmp);
			line.push_back(tmp);
		}
		file.close();
		
		for(int a=0;a<line.size();a++)
		{
			cout << line.at(a) << endl;
		}
	}
	else cout << "Error: Could not open file.";
	return 0;
}                                                                  


One last question:

How could I rewrite this so that I don't have to use the tmp string variable to get the input into the vector.pushback() method?
Last edited on
I don't think you can. (At least I haven't found a way).
Thanks. After I thought about it for a bit, I agree.
Well, you could

1
2
line.push_back( string() );
getline( file, line.back() );


or you could write your own wrapper:

1
2
3
4
5
6
7
8
string my_getline( ifstream& file ) {
    string tmp;
    getline( file, tmp );
    return tmp;
}

// ...
line.push_back( my_getline( file ) );


Neither of which buys you much....
Topic archived. No new replies allowed.