本文章的实现参考自<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;
}
本文根据《C++ Primer》一书,探讨如何用C++从文件读取字符串并写入到另一文件,关注标点符号处理、追加写入及ofstream和ifstream对象创建。代码示例中展示了如何将字符串以空格分隔写入'out_file',并讨论了使用ofstream构造错误。
813

被折叠的 条评论
为什么被折叠?



