首页 > 解决方案 > 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

所有同一行,实际上是文件的最后一行。谢谢!

标签: c++vector

解决方案


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]);
}

推荐阅读