C++ Again(1):文件读入与写出

来源:互联网 发布:淘宝店铺产品全部下架 编辑:程序博客网 时间:2024/06/04 19:23

本文章的实现参考自<C++ Primer>第一章第5节。

当前的任务是实现一个C++程序,能够从某个文件读入字符串并将字符串写入到另一个文件中。

实现代码如下:

#include <iostream>#include <fstream>#include <string>using namespace std;int main(){  ofstream outfile("out_file");  ifstream infile("in_file");  if(! infile){      cerr<<"error:unable to open file"<<endl;  return -1;  }  if(! outfile){      cerr<<"error:unable to open outfile"<<endl;  return -2;  }  string word;  while(infile >> word)  outfile << word << '~';  return 0;}

in_file:this is a cat and that is a dog

out_file:this~is~a~cat~and~that~is~a~dog~

需要探究的问题:1)标点符号如何处理?2)如何实现写入out_file的时候将新的字符串写入到文件的最后面,而不是取代文件的内容。

3)ofstream ifstream新建对象的语句

1)以空格切分字符串,所以标点符号与普通字符没有区别

3)使用ofstream out_file = new ofstream("out_file")出错;

#include <iostream>#include <fstream>#include <string>using namespace std;int main(){ // ofstream outfile("out_file"); // ifstream infile("in_file");ofstream outfile;ifstream infile;outfile.open("out_file");infile.open("in_file");  if(! infile){      cerr<<"error:unable to open file"<<endl;  return -1;  }  if(! outfile){      cerr<<"error:unable to open outfile"<<endl;  return -2;  }  string word;  while(infile >> word)  outfile << word << '~';  return 0;}

2)参考自:http://blog.sina.com.cn/s/blog_66474b160100wgan.html
#include <iostream>#include <fstream>#include <string>using namespace std;int main(){ // ofstream outfile("out_file"); // ifstream infile("in_file");ofstream outfile;ifstream infile;outfile.open("out_file",ios::app);infile.open("in_file");  if(! infile){      cerr<<"error:unable to open file"<<endl;  return -1;  }  if(! outfile){      cerr<<"error:unable to open outfile"<<endl;  return -2;  }  string word;  while(infile >> word)  outfile << word << '~';  return 0;}

原创粉丝点击