1

我想用 C++ 编写一个程序来读取一个文件,其中每个字段前面都有一个数字,表示它有多长。

问题是我读取了类对象中的每条记录;如何使类的属性动态化?

例如,如果该字段是“john”,它将在 4 字符数组中读取它。

我不想制作一个包含 1000 个元素的数组,因为最小内存使用量非常重要。

4

4 回答 4

3

使用std::string,它将调整大小以容纳您分配给它的内容。

于 2010-04-24T19:09:32.600 回答
2

如果您只想从文件中逐字读取,可以执行以下操作:

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

这会将文件中的所有单词放入 vectorwords中,尽管您会丢失空格。

于 2010-04-24T19:15:17.690 回答
1

我想记录之间没有空格,或者你只会写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
}
于 2010-04-24T19:24:12.750 回答
1

为此,您需要使用动态分配(直接或间接)。

如果直接,您需要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>

于 2010-04-24T19:25:15.080 回答