64,636
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
int i;
ofstream ofile("text.txt",ios_base::out);
for(i=0;i<4;i++)
{
ofile<<"Zhang"<<i<<endl;
}
ofile.close();
string str;
char line[101];
ifstream ifile("text.txt",ios_base::in);
for(i=0;i<4;i++)
{
ifile.getline(line,100);
cout<<line<<endl;
}
ifile.close();
return 0;
}
//正好前两天写过关于文件的程序,你看看吧
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
typedef struct{
char name[8];
char number[8];
char sex[4];
}DataType;
int main()
{
DataType one;
cout<<"Enter the information."<<endl;
cout<<"Name"<<setw(10)<<"Number"<<setw(10)<<"Sex"<<endl;
cin>>one.name>>one.number>>one.sex;
cout<<"Display the information."<<endl;
cout<<"Name"<<setw(10)<<"Number"<<setw(10)<<"Sex"<<endl;
cout<<one.name<<setw(10)<<one.number<<setw(10)<<one.sex<<endl;
cout<<"Save the information to file."<<endl;
ofstream outfile;
outfile.open("test.txt",ios::out);
if(!outfile.is_open())
{
cout<<"Can not open the file."<<endl;
exit(0);
}
else
{
outfile.clear();
outfile<<"Name"<<setw(10)<<"Number"<<setw(10)<<"Sex"<<endl;
outfile<<one.number<<setw(10)<<one.name<<setw(10)<<one.sex<<endl;
}
outfile.close();
cout<<"Read the information form the fiel"<<endl;
ifstream readfile;
readfile.open("test.txt",ios::in);
if(!readfile.is_open())
{
cout<<"Can not open the file"<<endl;
exit(0);
}
else
{
string line; //每次从文件读一行
while(!readfile.eof())
{
getline(readfile,line);
cout<<line<<endl;
}
}
readfile.close();
system("pause");
return 0;
}