Sta*_*uft 0 c++ file-io object data-structures
#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;
Run Code Online (Sandbox Code Playgroud)
}
示例文本文件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
Run Code Online (Sandbox Code Playgroud)
现在显然,我希望这个程序创建一个Stock对象的向量,它具有对象的适当的set/get功能:Stock(string, double, string)
.
完成后,我想打印出向量中每个对象的每个成员.
令我难以理解的一件事是fstream
,它如何破译空格和行尾,并智能地读取字符串/整数/双精度并将它们放入适当的数据类型?也许它不能......我必须添加一个全新的功能?
现在似乎我实际上并没有为循环的每次迭代创建一个新对象?我认为需要做一些事情:
portfolio.push_back(new Stock(string, double, string));
?我只是不完全确定如何达到这一点.
此外,该代码应与互换std::list
,以及std::vector
.该程序编译没有错误,但输出为零.
首先,迭代向量只有在它不为空时才有意义.所以删除该行:
for(StockIt i = portfolio.begin(); i != portfolio.end(); i++)
Run Code Online (Sandbox Code Playgroud)
因为否则将永远不会执行此循环的内容.
其次,输入读数有问题: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.
}
Run Code Online (Sandbox Code Playgroud)
这将读取由空格分隔的三个字段.