Re: [Dev-C++] How to work with *.txt files??
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Per W. <pw...@ia...> - 2004-09-18 20:03:50
|
Ouch.
Don't do that.
There is the vector template class in the stl.
Do not write a method that reallocates all strings every time.
First line - allocate one string.
Second line - allocate two strings.
Third line - allocate three strings.
...
By doing this, you manage to transform a linear operation - proportional
to number of lines in the file - to become O(n^2).
If you open a 100,000 line file, you would perform 100,000^2 / 2 or
5,000,000,000 string assigns.
Never add complexity when it isn't needed.
std::vector<std::string> strings;
and then
strings.push_back(line);
or
strings.reserve(10);
strings[n++] = line;
is a lot nicer code, and tremendously much more efficient.
/Per W
On Sat, 18 Sep 2004, hielke_prins wrote:
> >> How do I refer to each line of my *.txt file???
>
> /*
> If you don't have any clue how to read a simple textfile, the first
> thing you
> proably have to do is buying a good book on C(++). But here ya go.
>
> I usually read small plaintext files in a vector using a simple
> wrapperclass.
> Something like this (if you meant to write it in C++ at least),
> didn't test it:
> */
>
> Class Lines
> {
> string *d_line;
> unsigned d_nLines;
>
> public:
> Lines(istream streamIn);
> /*
> (of course you need some simple memberfunctions
> returning linecount and lines on a given index too)
> */
> }
>
> Lines::Lines(istream streamIn)
> :
> d_nLines(0)
> {
> string inputLine,
> *tempLine;
>
> while(getline(streamIn, inputLine))
> {
> d_nLines++;
> tempLine = new string[d_nLines];
> for(unsigned i = 0; i < d_nLines; i++)
> {
> tempLine[i] = d_line[i];
> }
> delete d_line;
> d_line = tempLine;
> }
> }
>
> Regards,
> Hielke
|