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;
  }  
發佈了71 篇原創文章 · 獲贊 0 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章