使用我的sales_data类编写一个简单的程序

Using my sales_data class to write a simple program

本文关键字:一个 简单 程序 sales 我的 data      更新时间:2023-10-16

我正在完成下面一本书中的练习:

使用您的sales_data类编写一个程序,读取几个同一isbn的事务,并计算每个isbn的次数发生

我已经写过这样的程序,在这个程序中,我必须输入一个数字列表,然后打印出每个数字出现的次数。

这是我的类的定义,书中提供给我完成这个任务:

#ifndef SALES_DATA_H
#define SALES_DATA_H 
#include <string>
struct Sales_data {
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0;
};
#endif

这是程序应该接收到的输入:

0-201-78345 1-x 19.99 (ISBN, units_sold, price to book)
0-201-78345 1-x 19.99 (same ISBN)
2-201-78345-z 2 26.99

输出应该是:

0-201-78345 x-1 OCCURS 2 times
2-201-78345-z OCCURS 1 times

我的程序不是读取所有的isbn并打印计数器,而是只在isbn不同时打印计数器。

这是我的代码:

#include <iostream>
#include "Sales_data.h"
#include <string>

int main()
{
Sales_data currVal,val; 
double price = 0; 
if (std::cin >> currVal.bookNo >> currVal.units_sold >> price) {
int cnt = 1; 
while (std::cin >> val.bookNo >> val.units_sold >> price) {
if (currVal.bookNo == val.bookNo)
++cnt; 
else {
std::cout << currVal.bookNo << " occurs" << cnt << " times" << std::endl; 
currVal = val; 
cnt = 1;
}//end of else
}//end of while
std::cout << currVal.bookNo << " occurs" << cnt << " times" << std::endl;
}// end of outhermost if 
system("pause");
}

而且,如果不插入文件结束符的序列,我的程序不会打印最后一个ISBN。

尝试使用std::map:

typedef std::map<Sales_Data, unsigned int> Container_Type;
Container_Time inventory;
//...
Sales_Data item;
// Assume Sales_Data has overloaded operator>>.
while (std::cin >> item)
{
  Container_Type::iterator iter = inventory.find(item);
  if (iter != inventory.end())
  {
    iter->second++; // Increment the occurances.
  }
  else
  {
     // New item, add to container.
     inventory[item] = 1;
  }
}

上面的代码还假设Sales_Data重载了operator==operator<

读取后,遍历容器,输出项及其出现次数。

相关文章: