views:

146

answers:

4

I want to make a program in C++ that reads a file where each field will have a number before it that indicates how long it is.

The problem is I read every record in object of a class; how do I make the attributes of the class dynamic?

For example if the field is "john" it will read it in a 4 char array.

I don't want to make an array of 1000 elements as minimum memory usage is very important.

+2  A: 

Use std::string, which will resize to be large enough to hold the contents you assign to it.

James McNellis
+2  A: 

If you just want to read in word by word from the file, you can do:

vector<string> words;
ifstream fin("words.txt");
string s;
while( fin >> s ) {
    words.push_back(s);
}

This will put all the words in the file into the vector words, though you will lose the whitespace.

Justin Ardini
A: 

I suppose there is no whitespace between records, or you would just write file >> record in a loop.

size_t cnt;
while ( in >> cnt ) { // parse number, needs not be followed by whitespace
    string data( cnt, 0 ); // perform just one malloc
    in.get( data[0], cnt ); // typically perform just one memcpy
    // do something with data
}
Potatoswatter
A: 

In order to do this, you need to use dynamic allocation (either directly or indirectly).

If directly, you need new[] and delete[]:

char *buffer = new char[length + 1];   // +1 if you want a terminating NUL byte

// and later
delete[] buffer;

If you are allowed to use boost, you can simplify that a bit by using boost::shared_array<>. With a shared_array, you don't have to manually delete the memory as the array wrapper will take care of that for you:

boost::shared_array<char> buffer(new char[length + 1]);

Finally, you can do dynamic allocation indirectly via classes like std::string or std::vector<char>.

R Samuel Klatchko