学习C/C++第十二天 项目双色球预测

现在开始边学习边做小项目

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>

#define NUM 7
#define CHAR_SIZEOF 64
#define BALL_SIZEOF 33

using namespace std;

bool statitics(const char *path, int ball_16[BALL_SIZEOF]);

int main(void)
{
	string filename;
	int ball_16[BALL_SIZEOF] = { 0 };    //一定要记得初始化

	cout << "请输入文件名:" << endl;
	cin >> filename;
	if (statitics(filename.c_str(), ball_16))    //统计成功
	{
		for (int i = 0; i < BALL_SIZEOF; i++)
		{
			cout << "第 " << i + 1 << " 号球出现次数:" << ball_16[i] << endl;
		}
	}
	else         //统计失败
	{
		cout << "统计出错!" << endl;
	}

	system("pause");
	return 0;
}

bool statitics(const char *path, int ball_16[BALL_SIZEOF])
{
	int result[NUM];
	ifstream file;
	int i = 0;
	char err_buf[CHAR_SIZEOF];

	//防御式编程:判断输入  如果 path 为空
	if (!path)
	{
		cerr << "path 为空,请检查" << endl;
		return false;
	}

	//打开文件
	file.open(path);
	if (file.fail())
	{
		//char err_buf[CHAR_SIZEOF];
		cerr << "打开输入文件出错。" << strerror_s(err_buf, CHAR_SIZEOF, errno) << endl;             //打开文件失败   strerror(errno)  返回字符串的一个说明
		return false;
	}

	//从数据文件中读取到数组,一行必须能读取到7个
	do
	{
		i = 0;

		for (i = 0; i < NUM; i++)
		{
			file >> result[i];
			if (file.eof())              //读取到文件的尾部
			{
				break;
			}

			if (file.fail())             //判断文件失败
			{
				cerr << "读取文件失败,原因:" << strerror_s(err_buf, CHAR_SIZEOF, errno) << endl;
				break;
			}
		}

		if (i == 0) break;           //记录正常结束

		//如果到最后未满7个  
		if (i < NUM)
		{
			cerr << "仅读到" << i << "个记录,预期读取7个" << endl;
			file.close();              //关闭文件
			return false;
		}

		//做统计
		for (i = 0; i < NUM; i++)
		{
			cout << " " << result[i];
		}
		cout << endl;

		//对读入的数据进行统计
		  //TODO:
		for (i = 0; i < NUM - 1; i++)
		{
			int index = *(result + i) - 1;             //33号球  存放在 数组[32]中
			if (index >= 0 && index < BALL_SIZEOF)
			{
				*(ball_16 + index) +=1;
			}
		}
	} while (1);

	file.close();
	return true;
}

上面是实现读取文本的代码
下面是文件:
在这里插入图片描述
在运行后要输入文本文件***.txt
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值