这是在网上看到的两个程序,已经不知道原作者是谁了,可能是流传太广了吧 嘿嘿
//Example : 从in.txt 文件中读入数据,并输出到out.txt中,输出的文件中每行之间有一空行相隔
------------------------------------方法一-----------------------------
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main (int){
string s;
ifstream inf;
inf.open("in.txt");
//打开输出文件
ofstream outf;
outf.open("out.txt");
//从in.txt 文件中读入数据,并输出到out.txt中
/*其中 getline(参1,参2); 作用是从 inf 指向的文件中
每次读入一行,把数据存到字符串s 中,从第一行开始
每读完一行后,系统自动地把指针指向下一行,不用人为
干预*/
while( getline(inf,s ) ){
outf << s << "/n/n"; //我这里并没有用到字符串
cout << s << endl << endl; //数组,而是只用了一个串
} //S,是因为我每次读入一行
//后,立即就把它输出到
//out.txt中,跟着读下一行
inf.close();
outf.close();
return 0;
}
----------------------------------方法二-----------------------------------
#include <fstream>
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
int main (int){
ifstream inf;
inf.open("in.txt");
ofstream outf;
outf.open("out.txt");
/*这道题有许多解法的,重要的要了它文件输入输出的原理
你可以一行行地读入,也可以一个字一个字地读入,或一个词
一个词地读入,整型或浮点型读入,看你定义的是哪种数据类型*/
char c;
inf >> noskipws; //不忽略空白,把每行最后那个'/n'
//也读进来。
while(inf >>c)
{
if (c == '/n'){ //遇到 '/n' 回车、换行。
outf << "/n/n"; //输出到文件
cout << "/n/n"; //输出到屏幕
}
else{
outf << c; //输出到文件
cout << c; //输出到屏幕
}
}
/* 同样的原理,从文件中读入单个字符,每次读入一个后,
系统自动地把指针指向下一个字,而不用你指定这次读哪个,
下次读哪个,除非你不想从第一个开始读,比如说:我想从
第100个字开始读,或者我想读最后50个字。这就需要调用
相应的函数,并指定相应的位置。*/
inf.close();
outf.close();
return 0;
}
下面是书上的两个例题
-------------------------------------第一个---------------------------------
#include <fstream.h>
int main()
{
ofstream fout("test.in");
if(!fout)
{
fout << "Cannot open output file/n";
return 1;
}
fout << 10 << " " << 12.34 << "/"This is a text file./"/n";
fout.close();
system("pause");
return 0;
}
--------------------------------------第二个----------------------------
#include <iostream.h>
#include <fstream.h>
int main()
{
ofstream fout("test1.in");
if(!fout)
{
fout << "Cannot open output file./n" << endl;
return 1;
}
fout << "Hello!" << endl;
fout << 100 << " " << 64 << endl;
fout.close();
ifstream fin("test1.in");
if(!fin)
{
fout << "Cannot openinput file." << endl;
return 1;
}
char str[20];
int i;
fin >> str >> i;
cout << str << " " << i << endl;
fin.close();
system("pause");
return 0;
}
*********************************** END