开发者

How to use length indicator in a C++ program

开发者 https://www.devze.com 2022-12-27 21:03 出处:网络
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.

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 t开发者_开发技巧he 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.


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


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.


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>.


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号