64,654
社区成员
发帖
与我相关
我的任务
分享
#include <iostream.h>
#include <fstream.h>
void main()
{
int a[6];
int i=0;
int max;
float avg;
char c[128];
fstream f("a.txt", ios::in|ios::out|ios::trunc);
while(i < 6)
{
if(cin>>a[i])
{
i++;
}
else
{
continue;
}
}
max = a[0];
avg = 0;
for(i=0; i<6; i++)
{
if(max < a[i])
{
max = a[i];
}
avg+=a[i];
f<<a[i]<<" ";
}
avg/=6;
f<<endl<<max<<endl<<avg<<endl;
f.seekp(ios::beg);
while(f.getline(c, 128))
{
cout<<c<<endl;
}
}
//对文件操作可以这么写,具体程序偶就不帮你做了,要相信自己能行^_^
#include <stdio.h>
#include <process.h>
void save(int num) //把数据写入文件
{
FILE *fp;
fp=fopen("d:\\1.txt","w");
if(fp==NULL)
{
printf("无法打开!");
exit(0);
}
fwrite(&num,sizeof(int),1,fp);
fclose(fp);
}
int load() //从文件读取数据
{
int num;
FILE *fp;
fp=fopen("d:\\1.txt","rb");
if(fp==NULL)
{
printf("无法打开!");
exit(0);
}
while(!feof(fp))
{
fread(&num,sizeof(int),1,fp);
}
return num;
fclose(fp);
}
void main()
{
int MaxValue=7;
save(MaxValue);
int GetMaxValue=load();
printf("%d\n",GetMaxValue);
}
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void main()
{
ofstream of("hello.txt");
of<<"hello world";
of.close();
ifstream ifs("hello.txt");
string s;
ifs>>s;
cout<<s;
ifs.close();
system("pause");
}
//随便写了一个,你看看吧!有问题我们在讨论!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int SIZE=6;
int main()
{
int a[SIZE];
int i=0;
int max=0;
double sum=0.0, avg=0.0;
cout<<"Enter six data: ";
while(i!=SIZE)
{
cin>>a[i];
++i;
}
for(i=0;i!=SIZE;++i)
{
if(a[i]>max)
max=a[i];
sum+=a[i];
}
avg=sum/SIZE;
//cout<<"MAX="<<max<<endl;
//cout<<"Average="<<avg<<endl;
ofstream outfile;//保存结果
outfile.open("result.txt",ios::out);
if(!outfile.is_open())
{
cerr<<"Can not open the file!"<<endl;
exit(0);
}
outfile<<"MAX="<<max<<endl<<"Average="<<avg<<endl;
outfile.close();
cout<<"Save the result end!"<<endl;
ifstream readfile;//从文件中读取内容
readfile.open("result.txt",ios::in);
readfile.clear();
if(!readfile.is_open())
{
cerr<<"Can not open the file!"<<endl;
exit(0);
}
string str;
cout<<"Read the file is:"<<endl;
while(readfile>>str)
cout<<str<<endl;
readfile.close();
system("pause");
return 0;
}