数据文件(输入): 最近一段时间出现的球的号码
统计结果(输出): 统计各号球出现次数, 存入数组
输入文件:
ball.txt
8 11 17 23 32 33 10
4 5 7 10 12 22 16
3 13 15 18 21 33 16
4 8 9 13 28 33 4
9 15 19 21 23 29 15
9 11 15 22 24 26 3
1 5 7 9 10 20 16
2 10 13 16 23 32 8
1 7 12 14 18 25 10
9 12 21 27 29 30 5
lottery_prediction.cpp
#include <string>
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;
#define NUM 33 //球号
#define NBALL 7 //一次6+1
bool statistics(const char* path, int ball[]) {
ifstream file;
int result[NUM];//数组可以用指针表示其值,如:*(result+i)==result[i]
if (!path) {
cerr << "path is NULL" << endl;
return false;//传递空指针
}
file.open(path);
if (file.fail()) {
cerr << "打开输入文件出错, 原因:" << strerror(errno) << endl;
return false;
}//文件打开成功,开始传值进入result
while (1) {//一行一行执行,行数未知故while循环,遇i==0时结束
int i = 0;
for (; i < NBALL; i++) {
file >> result[i];
if (file.eof()) {
break;//文末下一位存有eof
}
if (file.fail()) {
cerr << "读取文件失败, 原因:" << strerror(errno) << endl;
break;
}
}
//行末结束,继续录入下一行;若未达到行尾-??如何判断是否是行尾??file>>如何区分空格和回车??
//无法判断达到行尾,无法区分回车和空格,但若全部取得数不为7的倍数,认为输入文件出错
//if(i == NBALL) {
// continue;
//}
//打印这行数字并将出现数字累积到ball中
for (i = 0; i < NBALL; i++) {
cout << setw(3) << result[i];
int index = *(result + i) - 1;
if (index >= 0 && index <= NUM) {//判断-防御式编程
(*(ball + index))++;
}
}cout << endl;
if (file.eof()) break;//文末正常结束
if (i + 1 < NBALL) {
cerr << "仅读到" << i + 1 << "个,预期读取" << NBALL << "个" << endl;
file.close();
return false;
}
}
file.close();
return true;
}
int main() {
int ball[NUM] = { 0 };
//string filename;
//cout << "请输入文件名:";
//cin >> filename;
//statistics(filename.c_str(), ball);
if (statistics("ball.txt", ball)) {
//打印ball中存储的各号球出现次数
for (int i = 0; i < NUM; i++) {
cout << "第" << setw(2) << i + 1 << "号球出现次数:" << *(ball + i) << endl;
}
}
else
cerr << "统计出错!" << endl;
system("pause");
return 0;
}
输出结果: