先说结论
本题为C++primer课本书上一道题
我发现,只有理解读取的多条销售记录已经是【排列有序】的书名号
这样子才不会出错
书中没有提到,对于我这个小白来说
着实让我测试纠结了一阵子
测试段代码使用 整数来替代Sales_item的对象。
#include<iostream>
//#include"Sales_item.h"
using namespace std;
int main() {
int cnt = 1;
int t1, t2;
cout << "请输入若干条销售记录" << endl;
if (cin >> t1) {
while (cin >> t2)
{
if (t1 == t2) {
cnt++;
}
else//不相同
{//打印第一条销售记录
cout << t1 << "共有" << cnt << "条销售记录" << endl;
//并将下一条销售记录重新赋值给t1;
t1 = t2;
//计数器重新归1;
cnt = 1;
}
}//while
//相同则打印销售记录
cout << t1 << "共有" << cnt << "条销售记录" << endl;
}
else {
cout << "输入数据有误" << endl;
return -1;
}
return 0;
可见,如果输入的是有序的则输出正确
如果输入为无序的,则输出错误
以上就是我对本题的个人看法
最后附上原书代码
#include<iostream>
#include "Sales_item.h"
int main() {
Sales_item trans1, trans2;
int num = 1;
std::cout << "请输入若干条销售记录" << std::endl;
if (std::cin >> trans1) {
while (std::cin >> trans2) {
if (compareIsbn(trans1, trans2))//Isbn相同
num++;
else {
std::cout << trans1.isbn() << "共有" << num << "条销售记录" << std::endl;
trans1 = trans2;
num = 1;
}
}//while
std::cout << trans1.isbn() << "共有" << num << "条销售记录" << std::endl;
}
else {
std::cout << "输入数据有误" << std::endl;
return -1;
}
return 0;
}
the end
___________________________________
直到我看完了练习1.24
崩溃.....TAT