如何在 C++ 中使用长度指示器程序
我想用 C++ 编写一个程序来读取一个文件,其中每个字段前面都有一个数字,指示它的长度。
问题是我读取了类对象中的每条记录;如何使类的属性动态化?
例如,如果字段是“john”,它将以 4 字符数组的形式读取它。
我不想创建一个包含 1000 个元素的数组,因为最小内存使用量非常重要。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
std::string
,它将调整大小,使其足够大以容纳您分配给它的内容。Use
std::string
, which will resize to be large enough to hold the contents you assign to it.如果您只想从文件中逐字读取,您可以这样做:
这会将文件中的所有单词放入向量
words
中,尽管您会丢失空格。If you just want to read in word by word from the file, you can do:
This will put all the words in the file into the vector
words
, though you will lose the whitespace.为此,您需要使用动态分配(直接或间接)。
如果直接使用,则需要
new[]
和delete[]
:如果允许使用 boost,则可以使用
boost::shared_array< 来简化一点;>
。使用shared_array,您不必手动删除内存,因为数组包装器将为您处理这些事情:最后,您可以通过。
std::string
或<等类间接进行动态分配代码>std::vectorIn order to do this, you need to use dynamic allocation (either directly or indirectly).
If directly, you need
new[]
anddelete[]
: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:Finally, you can do dynamic allocation indirectly via classes like
std::string
orstd::vector<char>
.我想记录之间没有空格,或者您只需编写
file >>>在循环中记录
。I suppose there is no whitespace between records, or you would just write
file >> record
in a loop.