⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stocks.cpp

📁 C++&datastructure书籍源码,以前外教提供现在与大家共享
💻 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 name;
    string exchange;
    double price;
    int    shares;
    
    Stock()
     : name("dummy"),
       exchange("none"),
       price(0.0),
       shares(0)
    { }
    
    Stock(const string& n, const string& xc,
          double p, int ns)
     : name(n),
       exchange(xc),
       price(p),
       shares(ns)
    { }
};

class Portfolio
{
  public:
    Portfolio();
    void Read(const string& filename);
    
    void Print(ostream& out)   const;
    
  private:
    tvector<Stock> myStocks;
};

Portfolio::Portfolio()
  : myStocks(0)
{
    myStocks.reserve(20);   // start with room for 20 stocks
}

void Portfolio::Read(const string& filename)
{
    ifstream input(filename.c_str());
    string symbol, exchange, price, shares;
    
    while (input >> symbol >> exchange >> price >> shares)
    {    myStocks.push_back(Stock(symbol,exchange,atof(price),atoi(shares)));
    }
}

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].name << "\t"
             << myStocks[k].exchange << "\t"
             << setw(8) << myStocks[k].price << "\t"
             << setw(12) << myStocks[k].shares << endl;
    }
    cout << endl << "----" << endl << "# stocks: " << len << endl;
}

int main()
{
    string filename = PromptString("stock file ");
    Portfolio port;
    
    port.Read(filename);
    port.Print(cout);
    
    return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -