c++编程思想的一个习题

这是c++编程思想的第四章的15题,一开始看起来很简单,可是编程的时候还是浪费了些时间。贴出来,供大家参考下 

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

class Sale
{
private:
 string lastName;
 string firstName;
 int    ID;
 string phoneNum;
 double  Sales;
 double percent;
public:
 Sale(){};
 Sale(const string&ln,const string &fn,const int &id,const string &pn,const double &s,const double&p)
  :lastName(ln),firstName(fn),ID(id),phoneNum(pn),Sales(s),percent(p){}
 friend ostream & operator<<(ostream &os,const Sale &sale);
};

ostream & operator<<(ostream &os,const Sale &sale)
{
 os<<setiosflags(ios::left)<<setw(14)<<sale.lastName                   //必须加ios
  <<setw(15)<<sale.firstName
  <<setw(8)<<sale.ID
  <<setw(14)<<sale.phoneNum
  <<setw(12)<<fixed<<setprecision(2)<<sale.Sales                //fixed确定为小数点后的精度
  <<scientific<<uppercase<<sale.percent;                        //科学读数法
 return os;
}

int main()
{
 ifstream file_in("Exercise.txt");
 string country;
 string data;
 int id;
 string input[6];
 string phone(12,'-');
 double sales,percent;
 size_t startpos,endpos;
 
 while (getline(file_in,data))
 {
  if(data.size()<20) {
   country=data;
   cout<<setw(45)<<country<<endl;
   cout<<setw(50)<<"-------------------"<<endl;
   cout<<"*Last Name*   *FirstName*    *ID*    *PHONE*       *Sales*     *Percent*"<<endl;
   continue;
  }
  startpos=0;
  for(size_t m=0;m<6;m++)
  {
   endpos=data.find(",",startpos);                     //startpos容易忘记
   if (endpos==string::npos)                           //结尾处
    endpos=data.size();
   input[m]=data.substr(startpos,endpos-startpos);
   startpos=endpos+1;
  }
  sales=atof(input[4].c_str());                              //atof(const char *)
  percent=atof(input[5].c_str());
  id=0;                                                      //每次循环都要使用,清0
  for (size_t k=0;k<input[0].size();k++)
  {
   if (isdigit(input[0][k]))
    id=input[0][k]-0x30+id*16;
   else id=input[0][k]-0x37+id*16;
  }
  size_t i=0;
  for(;i<10-input[1].size();i++)
   phone[i]='x';
  for (size_t j=0;i<12;i++,j++)
  {
   if(i==3||i==7) phone[++i]=input[1][j];
   else phone[i]=input[1][j];
  }
  Sale mysale(input[2],input[3],id,phone,sales,percent);
  cout<<mysale<<endl;
 }
 system("pause");
 return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值