本文章的实现参考自<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)以空格切分字符串,所以标点符号与普通字符没有区别