我的条件最小搜索失败我该如何解决这个问题? C++

问题描述

我有一个如下所示的 input.txt:
(按顺序:垂钓者、比赛、鱼、重量)

JACK random3030 鱼 10 鱼 12.6
JOHN random3030 鱼 5.3 鱼 4.5
THOMAS xyz0501鲤鱼2鲤5鱼3鲤6
史密斯 xyz0501 鲤鱼 40 鱼 3

我想实现的是打印一条鲤鱼的最小重量。当同一行中有超过 1 条鲤鱼时,我的代码失败。所以输出应该是:

托马斯在比赛 xyz0501 中钓到了一条最小重量为 2 的鲤鱼

我的输出如下所示:

托马斯在比赛 xyz0501 中钓到了一条最小重量为 6 的鲤鱼

所以如果连续有超过 1 条鲤鱼,我的输出总是打印最新的,而不是最小的。重要的是要注意 input.txt 中可能没有一条鲤鱼。另外,如果我把它放在 input.txt 中:

史密斯 xyz0501 鲤鱼 1 鲤鱼 40 鱼 3

而不是这个:

史密斯 xyz0501 鲤鱼 40 鱼 3

我的输出还是一样的,应该是SMITH,因为他已经抓到了最小的重量。
我的代码

int main()
{
    string filename;
    cout<<"Enter the name of the input file,please: ";
    cin>>filename;

//conditional min search
try
{
    Contest e;
    double minWeight=999;
    ContestEnor t(filename);
    bool l = false;
    for(t.first(); !t.end(); t.next())
    {

        if(!l && t.current().weight < minWeight)
        {
            l=true;
            e=t.current();
            minWeight=t.current().weight;
        }
        else if(l && t.current().weight < minWeight)
        {
            if(e.weight < minWeight)
                e=t.current();
            minWeight=t.current().weight;
        }
    }
    cout<<e.angler<<" has cought a carp with the lowest weight of "<< minWeight <<" on contest "<<e.contest<<endl;
}
catch(ContestEnor::FileError err)
{
    cerr<<"Can't find the input file:"<<filename<<endl;
}  
}

权重.hpp

struct Contest
{
    string angler;
    string contest;
    int counter;
    double weight;
};


   //This is the enumerator   
class ContestEnor  
{  
private:  
    ifstream _f;  
    Contest _cur;  
    bool _end;   

public:
    enum FileError {MissingInputFile};
    ContestEnor(const string &str) throw (FileError);
    void first()
    {
        next();
    }
    void next();
    Contest current() const
    {
        return _cur;
    }
    bool end() const
    {
        return _end;
    }
};


ContestEnor::ContestEnor(const string &str) throw (FileError)
{
    _f.open(str);
    if(_f.fail())
        throw MissingInputFile;
}

void ContestEnor::next()
{
    string line;
    getline(_f,line);
    if( !(_end = _f.fail()) )
    {
        istringstream is(line);
        is >> _cur.angler >> _cur.contest;
        _cur.counter = 0;
        string fish;
        int _size;
        for( is >> fish >> _size ; !is.fail(); is >> fish >> _size )
        {
            if(fish == "carp")
                _cur.weight=_size;
        }
    }
}

我认为我的主要 for 循环与我的问题有关(感谢调试)但可能还有更多我不知道的。我最近开始更多地练习课程和东西,所以请尽量保持解决方案简单。谢谢。

解决方法

如果连续有超过 1 条鲤鱼,我的输出总是打印最新的,

我相信这是因为读取文件的代码只存储一行中的最后一条鲤鱼

    for( is >> fish >> _size ; !is.fail(); is >> fish >> _size )
    {
        if(fish == "carp")
            _cur.weight=_size;
    }

如果一行中有两条鲤鱼,这个循环将运行两次。第二次它将用第二个的权重覆盖第一个的权重。这就是为什么你只能看到每行最后一条鲤鱼的重量。

每条鲤鱼都应该有自己的记录(1:1)。如果一个渔夫钓到两条鲤鱼。那么渔夫应该有两条记录,每条鲤鱼一条(1:n)

文件阅读器每次遇到另一条鲤鱼时,都应该创建并存储一条新记录。