好吧,作为一个老菜鸟,还有第一章几道题实在写不下去了,直接写书店程序,这个书店程序只能满足2 2? 2 3 3 这种连续的情况,无法满足2 3 2 3这种情况。
?
首先上Sales_item.h头文件源码在哪找,这个文件在书本给出网站中,底部有个download,如图
下载那个GCC pre-C++ 11 compiler 2012文件。?
Sales_item.h源码如下:
#ifndef SALESITEM_H
#define SALESITEM_H
#include <iostream>
#include <string>
class Sales_item
{
public:
Sales_item(const std::string &book) :isbn(book), units_sold(0), revenue(0.0) {}
Sales_item(std::istream &is) { is >> *this; }
friend std::istream& operator>>(std::istream &, Sales_item &);
friend std::ostream& operator<<(std::ostream &, const Sales_item &);
public:
Sales_item & operator+=(const Sales_item&);
public:
double avg_price() const;
bool same_isbn(const Sales_item &rhs)const
{
return isbn == rhs.isbn;
}
Sales_item() :units_sold(0), revenue(0.0) {}
public:
std::string isbn;
unsigned units_sold;
double revenue;
};
using std::istream;
using std::ostream;
Sales_item operator+(const Sales_item &, const Sales_item &);
inline bool operator==(const Sales_item &lhs, const Sales_item &rhs)
{
return lhs.units_sold == rhs.units_sold && lhs.revenue == rhs.revenue && lhs.same_isbn(rhs);
}
inline bool operator!=(const Sales_item &lhs, const Sales_item &rhs)
{
return !(lhs == rhs);
}
inline Sales_item & Sales_item::operator +=(const Sales_item &rhs)
{
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
inline Sales_item operator+(const Sales_item &lhs, const Sales_item &rhs)
{
Sales_item ret(lhs);
ret += rhs;
return ret;
}
inline istream& operator>>(istream &in, Sales_item &s)
{
double price;
in >> s.isbn >> s.units_sold >> price;
if (in)
s.revenue = s.units_sold * price;
else
s = Sales_item();
return in;
}
inline ostream& operator<<(ostream &out, const Sales_item &s)
{
out << s.isbn << "\t" << s.units_sold << "\t" << s.revenue << "\t" << s.avg_price();
return out;
}
inline double Sales_item::avg_price() const
{
if (units_sold)
return revenue / units_sold;
else
return 0;
}
#endif
书店程序.cpp
#include<iostream>
using namespace std;
#include"Sales_item.h"
int main()
{
Sales_item total;//保存下一条交易的变量
if(std::cin >> total){
Sales_item trans;//保存和的变量
//读取并处理剩余交易记录
while (std::cin >> trans) {
//如果我们任处理相同的书
if (total.isbn() == trans.isbn()) {
total += trans;//更新销售额
}
else {
//打印前一本书的结果
std::cout << total << endl;
total = trans;//total现在表示下一本书的销售额
}
}
cout << total << endl;//打印最后一本书的结果
}
else {
//没有输入!警告
cerr << "No data?!" << endl;
return -1;
}
}
上面的程序运行会出现这种错误:
不知道怎么解决。?
|