【问题标题】:C++ Trying to store data from a text file to a vector of class ItemC ++尝试将数据从文本文件存储到类Item的向量中
【发布时间】:2021-12-25 04:44:40
【问题描述】:

编写一个程序来跟踪五金店的库存。这家商店出售各种商品。对于商店中的每件商品,将保留以下信息:商品 ID、商品名称、订购的件数、当前在商店中的件数、售出的件数、该商品的制造商价格和商店的售价。您的程序必须是菜单驱动的,为用户提供多种选择,例如检查商品是否在商店中、出售商品以及打印报告。输入数据后,按项目名称排序。此外,在商品售出后,更新相应的计数。最初,商店中(商品的)件数与订购的件数相同,售出的商品件数为零。

程序的输入是一个由以下形式的数据组成的文件:

itemID
itemName
pOrdered manufPrice sellingPrice
1111
Dishwasher
20 250.50 550.50
2222
Microwave
75 150.00 400.00
3333
Cooking Range
50 450.00 850.00
4444
Circular Saw
150 45.00 125.00

定义一个Item类的向量来存储每个item的信息。该程序必须至少包含以下功能:一个用于向向量输入数据,一个用于显示菜单,一个用于销售商品,一个用于为经理打印报告。

我的打印功能、二进制搜索功能和排序功能现在出现问题(这很可能是由于我在工作中错误地混合了 int 和 string 功能,但不知道如何解决)。任何帮助将不胜感激。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <string>
#include <limits>
#include <algorithm>

using namespace std;

class Item
{
private:
    int itemID = 0;
    string itemName = "";
    int pOrdered = 0;
    double manufPrice = 0;
    double sellingPrice = 0;

public:
    Item() {};//default constructor;
    Item(int ID, string name, int quantityOrdered, double mPrice, double          sPrice) //constructor with parameters for itemID, item name, products ordered, manufacturing price, and selling price
    {
        itemID = ID;
        itemName = name;
        pOrdered = quantityOrdered;
        manufPrice = mPrice;
        sellingPrice = sPrice;
    };  

    friend istream& operator>>(istream& inp, Item& item)
    {
        inp >> item.itemID;
        inp.ignore(numeric_limits<streamsize>::max(), '\n');
        getline(inp, item.itemName);
        inp >> item.pOrdered >> item.manufPrice >> item.sellingPrice;
        inp.ignore(numeric_limits<streamsize>::max(), '\n');
        return inp;
    };

    friend ostream& operator<<(ostream& os, const Item& item)
    {
        os << item.itemID;
        os << item.itemName; 
        os << item.pOrdered; 
        os << item.manufPrice; 
        os << item.sellingPrice; 
        return os; 
    };

};
void menu()
//menu() displays menu 
{
    //Menu choices for hardware store report
    cout << "Welcome to the Friendly Hardware Store!" << endl;
    cout << "Choose among the following options: " << endl;
    cout << "1. To see if an item is in the store. " << endl;
    cout << "2. To buy an item. " << endl;
    cout << "3. To check the price of an item. " << endl;
    cout << "4. To print the inventory. " << endl;
    cout << "9. To end the program. " << endl;
};

void getData(ifstream& inp, vector<Item>& items)
//getData() reads input file into vector of class Item
{
    Item item; 
    while (inp >> item)
        items.push_back(item); 
};

//binSearch returns the index of the data entry if searchItem is found; otherwise, it returns - 1 (not found)
int binSearch(vector<Item> items, string searchItem)
{
    sortData(items); //must sort the data before doing a binary search 
    int first = 0; 
    int size = items.size(); 
    int mid; 
    bool found = false; 

    while (first <= size && !found)
    {
        mid = (first + size) / 2; 
        if (items[mid] == searchItem) //error here w/ "=="
            found = true;
        else if (items[mid] > searchItem) //error here w/ ">"
            size = mid - 1;
        else
            first = mid + 1; 
    }
    if (found)
    {
        cout << searchItem << " is in the store." << endl;
        return mid; 
    }
    else
    {
        cout << searchItem << " is NOT in the store." << endl;
        return -1;
    }
    
};

//printReport() displays all of the data. 
//wont print any values, so is my ostream function written     `incorrectly or is is it my (auto p: items) function--written down below-- instead???`
void printReport(const vector<Item>& items)
{
    cout << "                           Friendly Hardware Store" << endl;
    cout << "itemID       itemName         pOrdered    pInStore    pSold        manufPrice     sellingPrice   " << endl;
    for (auto p : items)
    {
        cout << p << " ";
    }       
    cout << endl; 
};

//sortData() sorts data in the vector 
void sortData(vector<Item>& items)
{
    int min; 
    Item temp; 
    int size = items.size(); 
    for (int i = 0; i < size; i++)
    {
        min = i; 
        for (int j = i + 1; j < size; ++j)
//I get a "no operator "<" matches these operands error on the subsequent line..
            if (items[j] < items[min])
                min = j; 
        temp = items[i]; 
        items[i] = items[min]; 
        items[min] = temp; 
    }// end for 
}//end sort 
        
int main()
{
    menu();
    ifstream infile("storeInventory.txt");
    infile.open("storeInventory.txt"); //open the input file storeInventory.txt
    vector<Item> items;
    string search; 
    getData(infile, items); 
    int choice; //user's choice from the menu
    cin >> choice;
    
    switch (choice)
    {
    case 1:     
        cout << "Enter the name of the item: " << endl;
        cin >> search;
        binSearch(items, search);
        menu(); 
    case 2:
        makeSale(items);
    case 3:
        cout << "To check the price of an item." << endl;
    case 4:
        cout << "To print the inventory." << endl;
        printReport(items);
    case 9:
        cout << "The program will now terminate." << endl;
        break;
    default:
        cout << "Invalid input.";
    } //end switch statement

    infile.close(); //close the input file
    return 0; 
};

【问题讨论】:

标签: c++ class vector file-io


【解决方案1】:

我看到的几个问题:

  1. getData() 不处理itemIDitemName 之间以及sellingPrice 之后的换行符。后者可以通过以下事实对inp &gt;&gt; itemID 进行下一个Item 的调用将跳过换行符。但是,inp &gt;&gt; itemID 在输入缓冲区中留下了一个换行符,这会阻止getline(inp, itemName) 正确读取(请参阅Why does std::getline() skip input after a formatted extraction?)。

  2. getData() 根本没有循环,因为它预计会用ifstream 中的所有Items 填充items 向量,但它目前只读取1 Item

  3. main() 试图打开storeInventory.txt 文件两次,一次是在ifstream 的构造函数中,另一次是在其open() 方法中。 open() 将因此失败,因为文件已经打开,因此在继续使用 ifstream 输入之前将流置于您不是 clear()'ing 的错误状态。

  4. main() 在打开ifstream 后没有调用getData()

话虽如此,试试这个:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <string>
#include <limits>

using namespace std;

void getData(ifstream& inp, vector<Item>& items);

//sortData() sorts data in the vector 
void sortData(vector<Item>& items);

//binSearch returns the index of the data entry if searchItem is found; otherwise, it returns - 1 (not found)
int binSearch(vector<Item> items, string searchItem);

//printReport() displays all of the data. 
void printReport(const vector<Item>& items);

//makeSale() prompts user for item and number of pieces and displays the amount due (You don't need to remember total) 
void makeSale(vector<Item>& items);

class Item
{
private:
    int itemID = 0;
    string itemName = "";
    int pOrdered = 0;
    double manufPrice = 0;
    double sellingPrice = 0;

public:
    Item() = default; //default constructor; 
    Item(int ID, string name, int quantityOrdered, double mPrice, double sPrice) //constructor with parameters for itemID, item name, products ordered, manufacturing price, and selling price
    {
        itemID = ID;
        itemName = name;
        pOrdered = quantityOrdered;
        manufPrice = mPrice;
        sellingPrice = sPrice;
    }

    friend istream& operator>>(istream& inp, Item& item)
    {
        inp >> item.itemID;
        inp.ignore(numeric_limits<streamsize>::max(), '\n');
        getline(inp, item.itemName); 
        inp >> item.pOrdered >> item.manufPrice >> item.sellingPrice;
        inp.ignore(numeric_limits<streamsize>::max(), '\n');
        return inp;
    }
};

//getData() reads input file into vector of class Item
void getData(ifstream& inp, vector<Item>& items)
{
    Item item;
    while (inp >> item)
        items.push_back(item);
};

int main()
{
    menu(); //call menu function 
    ifstream infile("storeInventory.txt"); //open the input file 
    if (!infile)
    {
        cout << "Cannot open the input file.The program terminates. ";
        return 1; 
    }
    vector<Item> items;
    getData(infile, items);
    infile.close(); //close the input file
    // use items as needed...
    system("pause");
    return 0; 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 2019-06-01
    相关资源
    最近更新 更多