布尔函数的错误答案

wrong answer from boolean function

本文关键字:答案 错误 函数 布尔      更新时间:2023-10-16

我的布尔函数check_gift工作不正常。

我把一个txt文件复制到矢量giftstore中。现在我想检查商店里是否有给定的商品。为了测试函数check_gift,我从实际的txt文件中提取了一个项目,但函数给出了错误的答案。它返回false而不是true。

我做错了什么?

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdlib>
#include <string>
#include <cassert>
using namespace std;
typedef vector<string> Wishes;
int size(Wishes& w){ return static_cast<int>(w.size()); }

struct Wishlist
{
double budget;
Wishes wishes;
};

struct Gift
{
double price;
string name;
};
typedef vector<Gift> Giftstore;
int size(Giftstore& g) { return static_cast<int>(g.size()); }

void read_wishlist_into_struct(ifstream& infile, Wishlist& wishlist)
{
double b;
infile>>b;
wishlist.budget=b;
int i=0;
string name;
getline(infile,name);
while(infile)
{
wishlist.wishes.push_back(name);
i++;
getline(infile,name);
}
infile.close();
}

void show_wishlist(Wishlist wishlist)
{
cout<<"Budget: "<<wishlist.budget<<endl<<endl;
cout<<"Wishes: "<<endl;
for(int i=0; i<size(wishlist.wishes); i++)
{
cout<<wishlist.wishes[i]<<endl;
}
cout<<endl;
}

void read_giftstore_into_vector(ifstream& infile, Gift& gift, Giftstore& giftstore)
{
double p;
string name;
int i=0;
infile>>p;
while(infile)
{
gift.price=p;
getline(infile,name);
gift.name=name;
giftstore.push_back(gift);
i++;
infile>>p;
}
infile.close();
}
void show_giftstore(Giftstore giftstore)
{
cout<<"All possible gifts in giftstore: "<<endl<<endl;
for(int i=0; i<giftstore.size(); i++)
{
cout<<giftstore[i].price<<"t"<<giftstore[i].name<<endl;
}
cout<<endl;
}

bool check_gift(Giftstore giftstore, string giftname)
{
int i=0;
while(i<size(giftstore))
{
if(giftstore[i].name==giftname)
{
cout<<"Yes"<<endl;
return true;
}
else
{
i++;
}
}
return false;
}

void clear(Wishlist& b)
{
b.budget=0;
while(!b.wishes.empty())
{
b.wishes.pop_back();
}
}
void copy(Wishlist a, Wishlist& b)
{
b.budget=a.budget;
for (int i=0; i<size(b.wishes); i++)
{
b.wishes.push_back(a.wishes[i]);
}
}

int main ()
{
ifstream infile2("giftstore.txt");
Gift gift;
Giftstore giftstore;
read_giftstore_into_vector(infile2, gift, giftstore);
show_giftstore(giftstore);
string giftname;
giftname="dvd Up van Pixar";
bool x;
x=check_gift(giftstore, giftname);
cout<<"in store?: "<<x<<endl;
return 0;
}

了解如何调试。如果您无法在代码中逐行跟踪,那么请尝试保存某种日志。

目前,至少将其输出到控制台。

就你而言1.验证输入文件是否已成功打开2.阅读时打印出每份礼物。

这将是一个很好的开始方式。

如果您希望能够放入多个日志语句,然后再将其删除,则可以使用一个可以在一个位置关闭的宏。

日志记录对于继续运行到生产中的大型项目来说是一项相当棘手的技能,但您应该学会如何在短期内调试程序。

我们在这里甚至看不到您的输入文件中有什么。这就是为什么人们对你的问题投了反对票。

好的:现在你已经告诉我你的问题是你需要从你读到的每个字符串的前面修剪空白

有多种方法可以做到这一点,但

trimmed = s.substr( s.find_first_not_of(" nrt" ) );

目前可能有效。

然而,我最初的答案仍然成立:请学会调试。如果你在读入字符串时输出字符串,你就会看到这些前导空格。