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

本文介绍了一个使用C++编写的程序,该程序从文本文件中读取内容,并找出所有符合用户指定长度的单词。利用自定义的EQ_Len类和find_if算法实现了高效查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值