Essential C++ P34 练习


一、题目( Essential C++ P34 练习 1.7 )

输入两行以上的文字并存盘,
然后编写一个程序打开该文本文件,
将其中的每个字读取到一个 vector 对象中,;

遍历该 vector,将内容显示到 cout;

然后用泛型算法 sort() 对所有文字排序,
排序后的结果输入到另一个文件。



二、编码

#include <iostream>
using namespace std;
#include <fstream>
#include <vector>
#include <algorithm>


int main()
{
	
   ofstream ofs;
   ofs.open("F:\\DevCpp\\AgetLearn\\p34.txt",ios::out);
   ofs << "Hello my new world"  << endl; 
   ofs << "add oil add oil" << endl ;
   ofs << "lalallallalalla" << endl ;
   
   ifstream ifs; 
   ifs.open("F:\\DevCpp\\AgetLearn\\p34.txt",ios::in);
   
   
   if(!ifs.is_open())
   {
   	   cerr << "p34.txt 文件打开失败!" << endl;
	   return -1;	 
   }


   	  
   vector<string> vstr;
   string word; 
   while ( ifs >> word)
   {
   	  vstr.push_back(word);         
   }
   
   // 遍历一个 vector
   for( int ix=0; ix < vstr.size(); ++ix )
   {
		cout << vstr[ix] << " " ; 
   } 
   cout << endl; 

   
   sort( vstr.begin(), vstr.end() );

   
   ofstream sofs; 
   sofs.open("F:\\DevCpp\\AgetLearn\\p34sort.txt",ios::out);  
   
   // 遍历内容并输出到一个文件
   for( int ix=0; ix < vstr.size(); ++ix )
   {
		sofs << vstr[ix] << " " ; 
   } 
   sofs << endl; 
   
   
   if(!sofs.is_open())
   {
   	   cerr << "p34sort.txt 文件打开失败!" << endl;
	   return -1;	 
   }

	   
   ofs.close();
   ifs.close();
   sofs.close(); 
   return 0;
   
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值