//将文本文件排序后输出,并得到最长和最短的单词
#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;
}
#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;
}