c语言状态机系统

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

#include
#include
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;
}

 

你可能感兴趣的:(c++)