dynamic variables in classes

i need an array of strings to hold lines of a text file but i don't know how many lines i will have.
normally i would just need something like string lines[]; or vector<string> lines; but that's not working.
if thats not possible i could make a huge number of lines and define it to a certain value so i could check how much lines i have. something like string lines[10000] = "a"; but even that is not working.
could somebody help me?
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
35
36
37
38
39
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
class text
{
vector<string> lines;
public:
	text(string source);
	void output(int linecount);
};
text::text(string source)
{
	int x = 0;
	char buffer[10000];
	ifstream myfile;
	myfile.open(source.c_str());
	while(!myfile.eof()){
	myfile.getline(buffer,10000);
	lines[x] = buffer;
	x++;
	}
	myfile.close();
}
void text::output(int linecount)
{
	cout << lines[linecount] << endl;
}
int main()
{
	text preupdate("a.txt");
	preupdate.output(0);
	preupdate.output(1);
	preupdate.output(2);
	preupdate.output(3);
	system("PAUSE");
	return 0;
}

the code above doesn't return any errors with visual c++ express 2008 but crashes when run with an 'vector subscript out of range' error.
Last edited on
modify lines 20-22 to increase the vector size:
1
2
getline(myfile,templine); // declare 'templine' as string (instead of char buffer [10000], this will take lines of any length
lines.push_back(templine); // insert an element to the vector with the value of 'templine' 
thanks. got it working.
Topic archived. No new replies allowed.