#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream myfile;
const int nline=9;
int num[nline]={1,2,3,4,5,6,7,8,9};
double data[nline]={1,2,3,5,4,12,45,14,17};
myfile.open("Hellofile.txt",ios::out);
if(myfile.is_open())
{
cout<<"file open successful"<<endl;
for(int i=0;i<nline;i++)
{
myfile<<num[i]<<" "<<data[i]<<endl;
}
}
myfile.close();
return 0;
}
写入的结果
1 1
2 2
3 3
4 5
5 4
6 12
7 45
8 14
9 17
读取的代码
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream myfile;
const int nline=9;
myfile.open("Hellofile.txt",ios::in);
double data[nline];
int num[nline];
if(myfile.is_open())
{
cout<<"file open successful"<<endl;
for(int i=0;i<nline;i++)
{
myfile>>num[i]>>data[i];
cout<<num[i]<<" "<<data[i]<<endl;
}
}
myfile.close();
return 0;
}
读取结果:
1 1
2 2
3 3
4 5
5 4
6 12
7 45
8 14
9 17
读取文本的例子:getline(ifsream a, string b)
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
int main()
{
ifstream myFile;
myFile.open("HelloFile.txt", ios_base::in);
if (myFile.is_open())
{
cout << "File open successful. It contains: " << endl;
string fileContents;
while (myFile.good())
{
getline (myFile, fileContents);
cout << fileContents << endl;
}
cout << "Finished reading file, will close now" << endl;
myFile.close();
}
else
cout << "open() failed: check if file is in right folder" << endl;
return 0;
}
结果:
File open successful. It contains:
My first text file!
Hello file!
Finished reading file, will close now