c语言状态机系统

读取文件并实现了把里面的数字读取出来并加以求平均数 

#include<stdio.h>
#include<string.h>
using namespace std;
int a1[1000009];
int r = 0;
int sum = 0,flag = 0;
void swi(char s)
{
	if(s == '\254')
	{
		if(!flag)
		{
			a1[r] = sum;
			r++;	
		}
		flag = 0;
		sum = 0;
	}
	else if(s == '\243')
	{
		
	}
	else if(s == '\n')
	{
		if(!flag)
		{
			a1[r] = sum;
			r++;	
		}
		flag = 0;
		sum = 0;
	}
	else if(s == '0')
	{
		sum  = sum*10+(s-'0');
	}
	else if(s == '1')
	{
		sum  = sum*10+(s-'0');
	}
	else if(s == '2')
	{
		sum  = sum*10+(s-'0');
	}
	else if(s == '3')
	{
		sum  = sum*10+(s-'0');
	}
	else if(s == '4')
	{
		sum  = sum*10+(s-'0');
	}
	else if(s == '5')
	{
		sum  = sum*10+(s-'0');
	}
	else if(s == '6')
	{
		sum  = sum*10+(s-'0');
	}
	else if(s == '7')
	{
		sum  = sum*10+(s-'0');
	}
	else if(s == '8')
	{
		sum  = sum*10+(s-'0');
	}
	else if(s == '9')
	{
		sum  = sum*10+(s-'0');
	}
	else
	{
		flag = 1;
	}
}	//状态机 
int main()
{
	char a;
	/*
	fstream openfile("678.txt");// 文件位置及名称,记得双斜杠,文件名称是1.txt,其它的是路径
	if (!openfile)
	{
		cout << "open failed!" << endl;
		exit(1);
	}
	do {
		openfile.get(a);
		if (openfile.eof())
			break;
		//cout << a; // 存到 a,以每个字符存
		swi(a);
	} while (!openfile.eof());*/
	FILE *fp=NULL;
	fp = fopen("678.txt", "a+");//读写打开一个文本文件,允许读,或在文件末尾追加数据
		if (fp == NULL) {
			printf("文件打开失败!");
		}
			char ch = fgetc(fp);//判断文件是否为空
		if (ch == EOF) {
			printf("文件为空!\n");
			}
			rewind(fp);//将指针重置到第一行
			while (!feof(fp)) {//检测文件一共多少行
				ch = fgetc(fp);
				swi(ch);
			}
	if(sum != 0)
	{
		a1[r] = sum;
		r++;
	}
	long long value = 0;
	for(int i = 0;i < r;++i)
	{
		printf("%d\n",a1[i]);
		value += a1[i];
	}
	if(value == 0)
	{
		
	}
	else
	{
		value /= r;	
	}
	printf("%lld\n",value);
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

-lyslyslys

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值