C++文件操作

打开一个文件读入文本,对文本进行操作后存入另一个文件。

int  main( )
{
//读取文件内容
// string filename;
// cout<<"please input the filename: "<<flush;
// cin>>filename;

ifstream infile;//定义fstream对象并打开文件
infile.open("testFile.txt");

if(!infile)
{
cerr<<"error: unable to open file "<<endl;
return -1;
}

string str;
vector<string> vec;
while(getline(infile, str)) //每次读取一行文件内容存储到vector
//while(infile>>str) //每次读取一个文件里的单词存储到vector
{
vec.push_back(str);
}

//将文本输出
vector<string>::iterator index = vec.begin();
for( ; index !=vec.end(); ++index)
cout<<*index<<endl;

//将每个字母转换为大写字母后存到文件 resultfile.txt
ofstream outfile("resultfile.txt"); //定义fstream对象并打开文件
if(!outfile)
{
cerr<<"error: unable to open file: resultfile.txt"<<endl;
return -1;
}

//将每个字母都转换为大写字母
// for(index=vec.begin() ; index !=vec.end(); ++index)
// {
// for(string::size_type id=0; id!=index->size(); ++id)
// (*index)[id] = toupper((*index)[id]);
// cout<<*index<<endl; //输出到控制台
// outfile<<*index<<endl; //输出到文件
// }

//再将每个单词的首字母转换为大写字母
string word, line;
for(index=vec.begin(); index !=vec.end(); ++index) //一行一行的遍历
{
istringstream stream(*index); //定义istringstream对象并绑定到 *index
ostringstream stream2(line); //定义ostringstream对象并绑定到 line
while(stream>>word) //从对象stream中(已绑定到*index)提取每一行的每一个单词
{
word[0] = toupper(word[0]); //首字母转换
stream2<<word<<""; //将word插入到stream2对象(已绑定到line)(插入空格是为了分离单词)
}

*index = stream2.str(); //将stream2对象中的string对象(即line)返回给*index
cout<<*index<<endl; //输出到控制台
outfile<<*index<<endl; //输出到文件
}
return 1
}



posted @ 2011-11-21 15:50  oceany  阅读(289)  评论(0编辑  收藏  举报