📄 stocks2.cpp
字号:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
#include "tvector.h"
#include "strutils.h" // for atoi and atof
#include "prompt.h"
struct Stock
{
string symbol;
string exchange;
double price;
int shares;
Stock()
: symbol("dummy"),
exchange("none"),
price(0.0),
shares(0)
{ }
Stock(const string& n, const string& xc,
double p, int ns)
: symbol(n),
exchange(xc),
price(p),
shares(ns)
{ }
};
class Portfolio
{
public:
Portfolio();
void Read(const string& filesymbol);
void Add(const Stock& s);
void Print(ostream& out) const;
void Search(int lowPrice, Portfolio& p) const;
int Size() const;
private:
tvector<Stock> myStocks;
};
Portfolio::Portfolio()
: myStocks(0)
{
myStocks.reserve(20); // start with room for 20 stocks
}
void Portfolio::Add(const Stock& s)
{
int count = myStocks.size(); // # stocks before adding new one
myStocks.push_back(s); // vector size is updated
int loc = count;
// invariant: loc-1 is index of rightmost unprocessed stock
// for k in myStocks[loc+1..count], s < myStocks[s]
while (0 < loc && s.symbol <= myStocks[loc-1].symbol)
{ myStocks[loc] = myStocks[loc-1];
loc--;
}
myStocks[loc] = s;
}
void Portfolio::Read(const string& filesymbol)
{
ifstream input(filesymbol.c_str());
string symbol, exchange, price, shares;
while (input >> symbol >> exchange >> price >> shares)
{ //myStocks.push_back(Stock(symbol,exchange,atof(price),atoi(shares)));
Add(Stock(symbol,exchange,atof(price),atoi(shares)));
}
}
int Portfolio::Size() const
{
return myStocks.size();
}
void Portfolio::Print(ostream& out) const
{
int k;
int len = myStocks.size();
out.precision(3); // show 3 decimal places
out.setf(ios::fixed); // for every stock price
for(k=0; k < len; k++)
{ out << myStocks[k].symbol << "\t"
<< myStocks[k].exchange << "\t"
<< setw(8) << myStocks[k].price << "\t"
<< setw(12) << myStocks[k].shares << endl;
}
}
void Portfolio::Search(int lowPrice, Portfolio& p) const
// postcondition: make p a portfolio of all the stocks that cost more than lowPrice
{
int k;
int len = myStocks.size();
for(k=0; k < len; k++)
{ if (myStocks[k].price > lowPrice)
{ p.Add(myStocks[k]);
}
}
}
int main()
{
string filesymbol = PromptString("stock file ");
Portfolio port;
Portfolio costly;
port.Read(filesymbol);
port.Print(cout);
cout << endl << "----" << endl << "# stocks: " << port.Size() << endl;
int low = PromptRange("enter low price ",2,300);
port.Search(low,costly);
costly.Print(cout);
cout << "# matches = " << costly.Size() << endl;
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -