[英]My conditional minimum search fails. How can i solve this? C++
我有一个如下所示的 input.txt:
(按此顺序:垂钓者、比赛、鱼、重量)
杰克随机3030鱼10鱼12.6
JOHN random3030 鱼 5.3 鱼 4.5
THOMAS xyz0501 鲤鱼2 鲤鱼5 鱼3 鲤鱼6
史密斯 xyz0501 鲤鱼 40 鱼 3
我想要实现的是打印一条鲤鱼的最小重量。 当同一行中有超过 1 条鲤鱼时,我的代码会失败。 所以 output 应该是:
THOMAS 在比赛 xyz0501 上钓到了一条最小重量为 2 的鲤鱼
我的 output 看起来像这样:
THOMAS 在比赛 xyz0501 上钓到了一条最小重量为 6 的鲤鱼
因此,如果连续有超过 1 条鲤鱼,我的 output 总是打印最新的,而不是最小的。 需要注意的是,input.txt 中可能没有一条鲤鱼。 另外,如果我把它放在 input.txt 中:
史密斯 xyz0501 鲤鱼 1 鲤鱼 40 鱼 3
而不是这个:
史密斯 xyz0501 鲤鱼 40 鱼 3
我的 output 还是一样,但应该是 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;
}
}
}
我认为我的主要循环与我的问题有关(感谢调试),但可能还有更多我不知道的。 我最近开始在课程和其他东西上练习更多,所以请让解决方案尽可能简单。 谢谢你。
如果连续多条鲤鱼,我的 output 总是打印最新的,
我相信这是因为读取文件的代码仅存储一行中的最后一条鲤鱼
for( is >> fish >> _size ; !is.fail(); is >> fish >> _size )
{
if(fish == "carp")
_cur.weight=_size;
}
如果一行中有两条鲤鱼,此循环将运行两次。 第二次它将用第二次的权重覆盖第一次的权重。 这就是为什么你只能看到每行最后一条鲤鱼的重量。
每条鲤鱼都应该有自己的记录(1:1)。 如果一个渔夫钓到两条鲤鱼。 那么渔夫应该有两个记录,每条鲤鱼一个( 1:n )
每次文件阅读器遇到另一条鲤鱼时,它都应该创建并存储一条新记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.