从.txt文件初始化对象向量

Initializing a Vector of Objects from a .txt file

本文关键字:对象 向量 初始化 文件 txt      更新时间:2023-10-16
#include<iostream>
#include<vector>
#include<fstream>
#include "stock.h"
int main(){
    double balance =0, tempPrice=0;
    string tempStr;
    vector < Stock > portfolio;
    typedef vector<Stock>::iterator StockIt;
    ifstream fileIn( "Results.txt" );
    for(StockIt i = portfolio.begin(); i != portfolio.end(); i++)
    {
        while ( !fileIn.eof( ))
        {
            getline(fileIn,tempStr);
            i->setSymbol(tempStr);
            fileIn >> tempPrice;
            i->setPrice(tempPrice);
            getline(fileIn,tempStr);
            i->setDate(tempStr);
        }
        fileIn.close();
    }
    for(StockIt i = portfolio.begin(); i != portfolio.end(); i++){
        cout<<i->getSymbol() <<endl;
        cout<<i->getPrice() <<endl;
        cout<<i->getDate() <<endl;
    }
    return 0;

}

示例文本文件,Results.txt:

GOOG    569.964 11/17/2010
MSFT    29.62   11/17/2010
YHOO    15.38   11/17/2010
AAPL    199.92  11/17/2010

现在很明显,我希望这个程序创建一个Stock对象的向量,该向量具有对象的适当设置/获取功能:Stock(string, double, string)

完成后,我想打印出向量中每个对象的每个单独成员。

关于fstream,有一件事让我感到困惑,那就是它如何破译空格和行尾,并智能地读取字符串/ints/双精度,并将它们放入适当的数据类型中?也许它不能。。。我必须添加一个全新的功能?

现在看来,我实际上并没有为循环的每次迭代创建一个新对象?我认为需要做一些类似的事情

portfolio.push_back(new Stock(string, double, string));?我只是不完全确定如何做到这一点。

此外,此代码应可与std::liststd::vector互换。这个程序编译时没有错误,但是没有输出。

首先,只有当向量不为空时,对其进行迭代才有意义。所以删除行:

for(StockIt i = portfolio.begin(); i != portfolio.end(); i++)

因为否则这个循环的内容将永远不会被执行。

其次,您的输入读取有问题:您将getline用于第一个字段,这将把行上所有3个字段的值读取到tempStr变量中。

第三,您不应该使用while(!fileIn.eof())-eof函数只在您尝试读取文件末尾之后返回true。相反,使用:

while (fileIn >> symbol >> price >> date) {
    //here you should create a Stock object and call push_back on the vector.
}

这将读取由空格分隔的三个字段。

您的代码中很少有问题。第一个for循环在一个空的portfolio向量上运行,因为向量没有初始化(没有对象被推到它(,所以begin((和end((是相同的。您应该从fstream逐行读取,直到EOF,然后将对象推送到向量。读取的每一行,都应该将其拆分(标记化(为3个部分,并创建一个新的Stock对象以推送到向量中。

另一个方面的反馈是,无论何时使用stl迭代器,对循环使用++itr,它都会更快地运行