c++ - c ++将文件读入对象向量,然后复制到向量指针
问题描述
我正在编写一个程序来从文件中读取并将每一行放入一个对象中,并将该行的所有内容分隔到该对象中它们自己的变量中。我把那部分记下来了,只是为我定义的功能是这样的
void printSpecs(vector<watercraft *> inventory).
你能帮我把文件中的输入变成一个对象向量,然后将该向量传递给一个像上面那样的函数吗?
这是我到目前为止所拥有的,但它是不正确的。
vector <watercraft *> test;
ifstream inFile;
inFile.open("watercraft.txt", ios::in);
if(!inFile){
cout << "Something wrong with input file" << endl;
exit(0);
}
for(int i = 0; i < 18; i++){
watercraft tempPtr(inFile);
test.push_back(&tempPtr);
}
结果是这样
1: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
2: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
3: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
4: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
5: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
6: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
7: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
8: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
9: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
10: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
11: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
12: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
13: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
14: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
15: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
16: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
17: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
18: pontoon Bentley 200 Cruise Mercury 90 Silver 20 37795
所有同一行,实际上是文件的最后一行。谢谢!
解决方案
tempPtr
在其范围内是本地的,并在其范围结束时失效。因此,存储它的指针并在以后取消引用指针是危险的。
例如,您可以在堆上创建对象,这样它们就不会因退出作用域而被删除。
for(int i = 0; i < 18; i++){
test.push_back(new watercraft(inFile));
}
另一种选择是创建 的向量watercraft
,然后添加指向每个元素的指针。(不要在创建向量时添加元素,因为重新分配可能会使现有指针无效):
vector<watercraft> watercrafts;
for(int i = 0; i < 18; i++){
watercraft tempPtr(inFile);
watercrafts.push_back(tempPtr);
}
for (size_t i = 0; i < watercrafts.size(); i++){
test.push_back(&watercrafts[i]);
}
推荐阅读
- laravel - 在 ubuntu 中为 laravel 应用程序设置适当的权限
- docker - 子目录中的 Docker 集线器自动构建
- python - 递归函数查找到特定目标的所有路径
- c++ - 返回文件开头后,循环中的 ifstream 停留在相同的值上
- javascript - 使用 React 获取箭头函数的返回值
- java - 如何在没有 layout.xml 的情况下以编程方式创建 AdView
- html - 如何在浏览器放大/缩小期间保持 SVG 大小相同
- angular - 将 ng-template 从一个组件传递到另一个组件内部的 ng-select
- x86 - 如何在英特尔环网架构上选择引导处理器 (BSP)
- c# - Unity - 为什么带有图像的材料会出现故障?仅在构建中?