题目描述
定义CBook,属性包含书名(string),编者(string)、售价(double),出版社(string)。方法有:重载输入、输出。
定义友元函数find(CBook *book, int n, int &max1index,int &max2index)查找n本书中售价最高、次高的两本书,并通过引用返回其下标。若有相同售价最高、次高的两本书,按输入顺序输出第一本、第二本。
输入n,输入n本书的信息,调用上述友元函数,求价格最高的两本书下标,并按样例格式输出书信息。
输入
测试次数
每组测试数据格式如下:
n
n行书信息(书名,编者,售价,出版社)
输出
每组测试数据输出两行:
第一行:售价最高的书信息。
第二行:售价次高的书信息。
具体输出格式见样例,售价保留两位小数。书中间以空格分隔。
样例查看模式
正常显示查看格式
输入样例1 <-复制
输出样例1
提示
读取‘,’前的字符用 getline进行输入,如下所示
#include <string>
string name;
getline(cin, name, ',');
代码部分:
#include<iostream>
#include<iomanip>
#include<cstring>
#include<cmath>
#include <string>
using namespace std;
class cbook//每一本书的信息
{
string name;
string writer;
double price;
string press;
public:
cbook(){}
cbook(string na,string wr,double pr,string pre):name(na),writer(wr),price(pr),press(pre){}
void input()
{
cout << name << endl;
cout << writer << endl;
cout <<fixed<<setprecision(2)<< price << endl;
cout << press;
}
friend void find(cbook* book, int n, int& max1index, int& max2index)
{
double max1 = 0;
for (int i = 0; i < n; i++)
{
if (book[i].price > max1)
{
max1 = book[i].price;
max1index = i;//找到最高价格的书
}
}
double max2 = 0;
for (int i = 0; i < n; i++)
{
if (book[i].price > max2 && book[i].price != max1)
{
max2 = book[i].price;
max2index = i;//找到价格第二高的书
}
// 清空输入缓冲区
}
}
};
int main()
{
int t;
cin >> t;
int n;
string name, writer, press;
double price;
while (t--)
{
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cbook* book = new cbook[n];
string line;
for (int i = 0; i < n; i++)
{
getline(cin, line);
int com1 = line.find(',');//找出第一个逗号
int com2 = line.find(',', com1 + 1);//第二个逗号
int com3 = line.find(',', com2 + 1);//第三个逗号
//python从入门到精通,艾里克.马瑟斯,62.00,人民邮电出版社
book[i] = cbook(line.substr(0, com1), line.substr(com1 + 1, com2 - com1 - 1), stod(line.substr(com2 + 1, com3 - com2 - 1)), line.substr(com3 + 1));//利用substr函数和逗号分隔,把书名,编者,售价,出版社 读入数组中
}
int max1 = 0;
int max2 = 0;
find(book, n, max1, max2);
book[max1].input();
cout << endl;
cout << endl;
book[max2].input();
delete[]book;//注意释放动态数组
}
return 0;
}
注意事项以及知识:
cin.ignore(numeric_limits<streamsize>::max(), '\n');为
清空输入缓冲区,为了确保下次输入的数据不会受到上次输入数据的影响而改变了位置,避免影响到逗号的读取。
substr函数的运用:
专门用于将字符串转换为 double
类型的函数。