我想用 C++ 编写一个程序来读取一个文件,其中每个字段前面都有一个数字,表示它有多长。
问题是我读取了类对象中的每条记录;如何使类的属性动态化?
例如,如果该字段是“john”,它将在 4 字符数组中读取它。
我不想制作一个包含 1000 个元素的数组,因为最小内存使用量非常重要。
使用std::string
,它将调整大小以容纳您分配给它的内容。
如果您只想从文件中逐字读取,可以执行以下操作:
vector<string> words;
ifstream fin("words.txt");
string s;
while( fin >> s ) {
words.push_back(s);
}
这会将文件中的所有单词放入 vectorwords
中,尽管您会丢失空格。
我想记录之间没有空格,或者你只会写file >> record
一个循环。
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
}
为此,您需要使用动态分配(直接或间接)。
如果直接,您需要new[]
and delete[]
:
char *buffer = new char[length + 1]; // +1 if you want a terminating NUL byte
// and later
delete[] buffer;
如果你被允许使用 boost,你可以通过使用boost::shared_array<>
. 使用 shared_array,您不必手动删除内存,因为数组包装器会为您处理:
boost::shared_array<char> buffer(new char[length + 1]);
std::string
最后,您可以通过或之类的类间接进行动态分配std::vector<char>
。