本程序目的:统计输入的数据中每个值出现的个数,同时将其输出。
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(void)
{
int currVal = 0,val = 0;
if (cin >> currVal) //读取第一个数,并确保确实有数据可以处理
{
int count = 1;
while (cin >> val)//读取剩余的数
{
if (currVal == val)
{
++count;
}
else
{
cout << currVal << " occurs " << count << " times " << endl;
currVal = val;
count = 1;
}
}
cout << currVal << " occurs " << count << " times " << endl;//打印文件中最后一个值的个数
}
system("pause"); //固定语句
return 0;//固定语句
}
两个程序意义差不到太多。
首先要用cin输入一个值,作为初始量。
然后可以cin多组数据,比较后一个数据和前一个数据的isbn是否一样,一样的话total+=trans。更新total值。
不一样,就将前一个数据的total输出,并且把当前trans作为total。
最后一组输入量,由于没有再进来的量了,因此,在while循环外面把total输出。
#include <iostream>
#include "Sales_item.h"
#include <stdlib.h>
using namespace std;
int main(void)
{
Sales_item total;
if (cin >> total)
{
Sales_item trans;
while (cin >> trans)
{
if (total.isbn() == trans.isbn()) {
total += trans;
}
else
{
cout << total << endl;
total = trans;
}
}
cout << total << endl;
}
else {
cerr << "no data" << endl;
return -1;
}
system("pause"); //固定语句
return 0;//固定语句
}