废话不多说,直接上代码。。。
#include <iostream>
#include <Windows.h>
#include <fstream>
#include <string>
// 统计双色球出现次数项目实现
using namespace std;
#define BALL 33
#define NUM 7
bool boll(const char *path, int ball_1_6[], int len) {
int result[NUM]; // 读取一行的七个数据暂存区
ifstream file; // 文件指针 // 相当于C语言 FILE *file;
int i=0;
// 判断指针是否为空指针
if (!path) {
cerr << "path is NULL" << endl;
return false;
}
// 打开文件
file.open(path);
if(file.fail()) {
cerr << "打开文件失败:" << strerror(errno) << endl;
return false;
}
// 从文件中读取数据到数组,一行必须能读取7个
do {
for(i=0; i<NUM; i++) { // for循环读取一行
file >> result[i]; // 读取一个数据
if (file.eof()) { // 当文件读取到末尾
break;
}
if (file.fail()) { // 当文件读取失败
cout << "读取文件失败:" << strerror(errno) << endl;
break;
}
}
// for循环结束 i == 7
if (i == 0) break; // 当文件读取完了,也就是空行,i == 0
// 如果没有读取到7个数据
if (i < NUM) {
cout << "紧读取到" << i << "个数据,预期读取7个数据" << endl;
file.close(); // 关闭文件
return false;
}
for(i=0; i<NUM; i++) {
cout << "\t" << *(result+i);
}
cout << endl;
for (i=0; i<NUM; i++) {
int index = *(result+i)-1; // 计算出数字的下标
// 数组下标必须在0-32 // 防御式编程
if (index >=0 && index < BALL) {
(*(ball_1_6 + index))++; // 根据下标累加1
}
}
} while (1);
file.close();
return true;
}
int main(void) {
string filename; // 文件名
int ball_1_6[BALL] = {0}; // 统计出现次数数组
cout << "请输入文件名:";
cin >> filename;
if (boll(filename.c_str(), ball_1_6, BALL)) {
cout << endl << "===================" << endl << endl;
for (int i=0; i<BALL; i++) {
cout << i+1 << "号球出现的次数是:" << *(ball_1_6+i) << endl;
}
} else {
cout << "传输失败!" << endl;
}
system("pause");
return 0;
}
还有最后一个球的统计方法类型,这里就不显示了。。。