现在的位置: 首页 > 综合 > 正文

函数对象的应用:在指定的文件中显示指定长度的字符串

2013年09月16日 ⁄ 综合 ⁄ 共 1079字 ⁄ 字号 评论关闭

#include<iostream>

#include<vector>

#include<string>

#include<fstream>

#include<sstream>

#include<functional>

#include<algorithm>

 

using namespace std;

 

class EQ_Len

{

private:

    string::size_typebound;

public:

    EQ_Len(size_tsize):bound(size)

    {

    }

    inline booloperator()(const string& str)

    {

        returnstr.size()==bound;

    }

};

void main()

{

    stringfilename;

    cout<<"请输入要打开的文件名:";

    cin>>filename;

    fstreamfile(filename.c_str());

    if(!file)

    {

        cerr<<"路径非法,不能打开该文件!"<<endl;

        return;

    }

    vector<string>v;

    string line;

    while(getline(file,line))

    {

        stringstreamss(line);

        stringword;

        while(ss>>word)

        {

            v.push_back(word);

        }

    }

    int len;

    cout<<"输入要查找单词的长度:";

    cin>>len;

    int row=0;

    vector<string>::iteratorit=v.begin();

    while(it!=v.end())

    {

        it=find_if(it,v.end(),EQ_Len(len));

        if(it!=v.end())

        {

            cout<<*it++<<"";

            row++;

            if(row==8)

            {

                row=0;

                cout<<endl<<"-----------------------------------------"<<endl;

            }

        }

    }

    cout<<endl;

}

抱歉!评论已关闭.