问题描述
我有一个用 C++ 编码的数据库模拟器,它的工作方式本质上是用户说 "insert 'item' 'quantity' 'price'"
,其中 item
是一个字符串,而 quantity
/price
是一个整数。
我遇到的问题是,每当用户输入 "insert"
而没有输入其他字段时,就会弹出“向量下标超出范围”错误。
例如,"insert keyboard 20"
会给我错误,因为没有给出价格。
我认为这是因为这些值最初没有初始化,但我尝试这样做并且没有任何改变。我已经尝试在结构中将它们初始化为 0,但它仍然让我中止程序。我想这是因为我使用的类正在搜索 3 个变量,当它没有得到它们时,它就会崩溃。
老实说,我不确定有没有办法用我当前的代码来做到这一点(我真的无法彻底修改它,他们想要课程),但我想我会和你一起在黑暗中试一试技术大师。
以下是我正在使用的两个类。
编辑我创建的结构数据库的类:
class ProductDB
{
public:
ProductDB() = default;
~ProductDB() = default;
//Commands to give ProductDB control over appending,removing,updating,finding,and printing
void append(const string& name,int quantity,double price);
private:
vector<Product> items;
//initialize sequence counter for append
int seq = 0;
//check for unique names using set function
set<string> productNames;
};
这里是将信息插入数据库的类:
//class to append
void ProductDB::append(const string& name,double price)
{
if (quantity <= 0 || price <= 0) {
cout << "Input Error: Please enter a quantity" << endl;
return;
}
if (productNames.find(name) != productNames.end()) {
cout << "Input Error: That name already exists,Please enter an unique name!" << endl;
return;
}
Product item;
//running total for sequence
item.id = ++seq;
item.name = name;
item.quantity = quantity;
item.price = price;
items.push_back(item);
// insert name in database as the product gets inserted
productNames.insert(name);
cout << "Entry: '" << item.name << "' inserted successfully!" << endl;
}
这是我给全班打电话的地方:
//insert command
if (cmdInput[0] == "insert")
{
string name = cmdInput[1];
int quantity = stoi(cmdInput[2]);
double price = stod(cmdInput[3]);
itemsDB.append(name,quantity,price);
}
解决方法
像这样:
//insert command
if (cmdInput[0] == "insert")
{
if( (int)cmdInput.size() < 4 ) {
std:cout << "Not enough input params\n";
}
else {
string name = cmdInput[1];
int quantity = stoi(cmdInput[2]);
double price = stod(cmdInput[3]);
itemsDB.append(name,quantity,price);
}
}
这种技术称为“防火墙”:编写代码,在开始处理输入之前检查输入的正确性。这将所有混乱的 if 语句和错误处理与处理代码分开,处理代码可以在假设一切正常的情况下继续进行,因此可以以清晰直接的方式进行编码,易于理解和维护。