C++文本文件处理示例(文件输入输出流)

       //将文本文件排序后输出,并得到最长和最短的单词

  #include <iostream>
  #include <fstream>
  #include <string>
  #include <vector>
  #include <algorithm>
  using namespace std;
  int main()
  {
  string ifile;
  cout << "Please enter file to sort: ";
  cin >> ifile;
  // 构造一个 ifstream 输入文件对象
  ifstream infile( ifile.c_str() );
  if( ! infile ) {
  cerr << "error: unable to open input file: "
  << ifile << endl;
  return -1;
  }
  string ofile = ifile + ".sort";
  
  // 构造一个 ofstream 输出文件对象
  ofstream outfile( ofile.c_str() );
  if( !outfile ) {
  cerr << "error: unable to open output file: "
  << ofile << endl;
  return -2;
  }
  string buffer;
  vector< string> text;
  vector< string> min;
  vector< string> max;
  int little,big;
  int cnt = 1;
  while ( infile >> buffer )
  {
   text.push_back( buffer );
   if (cnt==1)
   {
   little=buffer.size ();
   big=buffer.size ();
   }
   if (buffer.size ()<=little)
   {
   if (buffer.size ()<little)
   min.clear();
   min.push_back (buffer);
   little=buffer.size ();
   }
   if (buffer.size ()>=big)
   {
   if (buffer.size ()>big)
   max.clear();
   max.push_back (buffer);
   big=buffer.size ();
   }
  
   cnt++;
   //cout << buffer << ( cnt++ % 8 ? " " : "/n" );
  }
  cout << "长度最短的单词有:" << endl;
  for(int i=0;i<min.size ();i++)
  {
   cout << min[i] << endl;
  }
  cout << "长度最长的单词有:" << endl;
  for(int i=0;i<max.size ();i++)
  {
   cout << max[i] << endl;
  }
  sort( text.begin(), text.end() );
  // ok: 把排序后的词打印到 outfile
  vector<string >::iterator iter = text.begin();
  for ( cnt = 1; iter != text.end(); ++iter, ++cnt )
  outfile << *iter << (cnt%8 ? " " : "/n" );
  return 0;
  }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值