是否有一种方法要求输入所有字段以避免矢量下标超出范围的错误



我有一个用C++编码的数据库模拟器,它的工作方式本质上是用户说"insert 'item' 'quantity' 'price'"item是字符串,quantity/price是int。

我遇到的问题是,每当用户输入"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, int quantity, 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 paramsn";
}
else {
string name = cmdInput[1];
int quantity = stoi(cmdInput[2]);
double price = stod(cmdInput[3]);
itemsDB.append(name, quantity, price);
}
}

这种技术被称为";防火墙":编写代码,在开始处理输入之前检查输入的正确性。这将所有混乱的if语句和错误处理与处理代码分开,处理代码可以在假设一切正常的情况下进行,因此可以以清晰直接的方式进行编码,易于理解和维护。

最新更新