比赛中控制从文件输入输出,freopen或fopen版

比赛或者练习中,输入重复内容进行debug让人头疼,因此,平时练习,可以在文件里输入输出,避免命令行的繁琐。

另外:c语言中文件打开模式

  • freopen版,从input.txt输入,printf会打印到文件output.txt中。
#include<stdio.h>
int main()
{
	/*重定向版输入输出只要加入这两句话即可 
	freopen("D:\\代码\\input.txt","r",stdin);
	freopen("D:\\代码\\output.txt","w",stdout);

        在不需要从文件输入输出后,可以转换到控制台输入输出:
        freopen("CON","r",stdin);
        freopen("CON","w",stdout);
	*/
	
	int x,min,max,s=0;
	double n=0;
	scanf("%d",&x);
	min=max=x;
	n++;
	s+=x;
	
	while(scanf("%d",&x)==1)
	{
		s+=x;
		if(x>max)max=x;
		if(x<min)min=x;
		n++;
	}
	printf("%d %d %.3lf",min,max,double(s/n));
	
	return 0;
} 
  • fopen版,

注意

1.要定义FILE 类型的指针,它们各自指向要读取和写入的文件。

2.要用fscanf,fprintf函数。

3.关闭文件,节省资源。

#include<stdio.h>
int main()
{
	/*重定向版输入输出只要加入这两句话即可 
	freopen("D:\\代码\\input.txt","r",stdin);
	freopen("D:\\代码\\output.txt","w",stdout);
	*/
	
	FILE *fin,*fout;
	fin=fopen("D:\\代码\\input.txt","rb");
	fout=fopen("D:\\代码\\output.txt","wb"); 
	int x,min,max,s=0;
	double n=0;
	fscanf(fin,"%d",&x);
	min=max=x;
	n++;
	s+=x;
	
	while(fscanf(fin,"%d",&x)==1)
	{
		s+=x;
		if(x>max)max=x;
		if(x<min)min=x;
		n++;
	}
	fprintf(fout,"%d %d %.3lf",min,max,double(s/n));
	fclose(fin);
	fclose(fout);
	
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/GooTal/article/details/82726247
今日推荐