【发布时间】:2020-11-24 23:08:38
【问题描述】:
我正在上 C++ 简介课程,我们的一项任务是创建一个在线商店。我们的问题之一是为库存创建一个搜索功能,使用线性搜索,然后显示该商品的相应价格、库存和可运输性。
出于某种原因,无论我如何尝试调整它,它总是返回 false 进行搜索,并且商店不提供该商品,即使我输入了我知道的商品项目数组。
例如,如果我在getline 中键入Moon Pie(在我的数组中),它仍会以-1 的形式返回,就像不是一样。这段代码有什么明显错误吗?
这是我的 inputInventory.txt
Moon Pie 3.50 15 1
Cosmic Brownie 2.00 12 0
Moon Shine 7.00 7 1
Astronaut Icecream 4.00 11 1
Neptune Nuggets 2.50 30 1
Venus Vodka 6.50 10 1
Planet Pop 4.50 20 0
Starry Salad 3.00 15 0
Celeste Cakes 5.00 11 1
Plasma Potion 9.99 4 1
Star Fruit 2.50 10 1
Sun-dae 7.00 20 0
Moon Cheese 5.00 10 1
Milky Way Milkshake 6.50 5 0
Pluto Pie 7.00 9 10
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
const int MAX = 15;
void searchInventory(string itemNames[], double itemCost[], int itemNoShip[MAX][2]);
int linearSearch(string arr[], int size, string value);
int main() {
int input;
string items[MAX];
double priceItems[MAX];
int noItems[MAX][2];
cout << "\n1. Read in Inventory\n";
cout << "2. Display Inventory\n";
cin >> input;
while (input > 2 || input < 1) {
cout << "An error has occured. Please input a value 1 - 2. >> ";
cin >> input;
}
switch (input) {
case 1:
if (readInventory(items, priceItems, noItems) == true) {
cout << "\nReading the file...\n";
}
break;
case 2:
searchInventory(items, priceItems, noItems);
break;
}
}
bool readInventory(string itemNames[], double itemCost[], int itemNoShip[MAX][2]) {
bool fileRead = false;
ifstream inputFile; // Pointer
inputFile.open("inputInventory.txt");
if (inputFile) // Test if file opened
{
for (int row = 0; row < MAX; row++) {
getline(inputFile, itemNames[row], '\t');
inputFile >> itemCost[row];
inputFile >> itemNoShip[row][0];
inputFile >> itemNoShip[row][1];
}
fileRead = true;
inputFile.close();
}
return fileRead;
}
void searchInventory(string itemNames[], double itemCost[], int itemNoShip[MAX][2]) {
string search;
int result;
int position;
cout << "Please type the name of the item you are looking for. > ";
cin.ignore();
getline(cin,search);
result = linearSearch(itemNames, MAX, search);
cout << result;
if (result >= 0) {
cout << "\nYour item was found!\n";
cout << itemNames[result] << itemCost[result] << itemNoShip[result][0] << "Shippable:" << itemNoShip[result][1];
}
else {
cout << "\nThis item was not found in the list.";
}
}
int linearSearch(string arr[], int size, string value) {
int position;
int index;
for (index = 0; index < size; index++) {
if (arr[index] == value) {
position = index;
}
else {
position = -1;
}
}
return position;
}
【问题讨论】:
-
linearSearch()LGTM,您能否分享一个完整、最小且可重现的示例?例如,您的数组是如何填充的?value是否在调用搜索方法之前存储了期望值?你确定position在搜索方法中被初始化了吗? -
添加到 gsamaras,我们需要知道你传递给这个函数的内容。
-
linearSearch如果for循环至少没有执行一次,则返回一个未初始化的值。如果size为 0 会怎样? -
除此之外,我们看到的只是变量。我们没有看到正在使用的实际值。因为它们是从
cin输入的。如果您没有输入您声称正在使用的值怎么办?您应该对这些值进行硬编码,而不是使用cin来验证linearSearch函数是否确实有效。或者您可以简单地输出:cout << "\nThis item " << search << " was not found in the list.";,这样您就可以看到您实际搜索的内容。
标签: c++ arrays linear-search