从.txt文件初始化对象向量
Initializing a Vector of Objects from a .txt file
#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::list
和std::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,它都会更快地运行
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 从多个源构造一个对象,包括一个对象向量
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 对象 C++ 向量的 STL 容器
- 初始化C++中的对象向量
- 从自定义类获取对象向量中的 max 元素
- 如何在 c++ 中打印存档中的对象向量
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 尝试重载输出运算符时,我无法遍历对象向量
- 如何在C++中打印对象向量的内容
- 打印出对象向量中的每个元素C++
- 在 c++ 的构造函数中分配对象向量时出错
- 遍历对象向量,并找到与从文本文件中提取的对象匹配的变量
- 对象向量是否在堆或堆栈上分配C++?
- 基于不同字段的对象向量的排序功能
- 有没有一种简单的方法可以在对象向量上调用构造函数?
- 用rapidjson读取子对象向量
- 尝试使用比较运算符对对象向量进行排序
- 如何用对象向量重载 cin(>>)
- 如何将某个元素从shared_ptr擦除到对象向量?