C/C ++ File Operations

Source: Internet
Author: User

First, take the data statistics as an example:

Calculates the maximum, minimum, and average values of a set of data.

If you do not need file operations, the following is the case:

#include<iostream>#include<fstream>#include<string>using namespace std;int main(){int x,n=0,min=99999,max=-99999,s=0;while(scanf("%d",&x)==1){s+=x;if(x<min) min=x;if(x>max) max=x;n++;}printf("%d %d %.3lf\n",min,max,double(s/n));return 0;}

It is troublesome to input new data each time. You can use the file method to calculate the data in a file.

The simplest way to use a file is to use input/output redirection. You can simply write the following two statements at the main function entry:

Freopen ("input.txt", "r", stdin );
Freopen ("output.txt", "W", stdout );

Then, scanfwill be read from the input.txt file and written to the output.txt file.

#include<iostream>#include<fstream>#include<string>using namespace std;int main(){int x,n=0,min=99999,max=-99999,s=0;while(scanf("%d",&x)==1){s+=x;if(x<min) min=x;if(x>max) max=x;n++;}printf("%d %d %.3lf\n",min,max,double(s/n));return 0;}

You can also use fopen without using redirection:

#include<stdio.h>#define INF 1000000int main(){FILE*fin,*fout;fin=fopen("data.in.txt","rb");fout=fopen("data.out.txt","wb");int x,n=0,min=INF,max=-INF,s=0;while(fscanf(fin,"%d",&x)==1){s+=x;if(x<min) min=x;if(x>max) max=x;n++;}fprintf(fout,"%d %d %.3lf",min,max,(double)s/n);fclose(fin);fclose(fout);return 0;}

Reading and Writing files in C ++:

#include <iostream>#include <fstream>#define INF 1000000using namespace std;ifstream fin("input.txt");ofstream fout("output.txt");int main(){int x,n=0,max=-INF,min=INF;double s=0.0;while(fin>>x) {s+=x;if(x<min) min=x;if(x>max) max=x;n++;}fout<<min<<" "<<max<<" "<<s/n<<endl;return 0;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.