Редактирование элементов в текстовом файле c ++ - PullRequest
0 голосов
/ 10 апреля 2020

Я создал систему меню для ресторана. Используя массивы, я создал систему для добавления новых элементов в меню и их печати в текстовом файле. Это все работает нормально.

Проблема возникает, когда мне нужно отредактировать элемент, например, если я добавил 3 блюда и использую опцию редактирования, редактируется только первая строка текстового файла и элемент число возвращается к 0, когда минимальное значение всегда должно быть 1.

Как я могу заставить эту работу работать, чтобы, если я редактирую элемент 3, редактирование будет отображаться в текстовом файле в строке 3 вместо перезаписи строки 1?

Я не уверен, в чем проблема, поэтому я прилагаю все файлы проекта, так как это не слишком долго.

Заранее спасибо

.h файл:

 #ifndef RESTAURANTMENU_ITEMS_H
#define RESTAURANTMENU_ITEMS_H

#define MAX_ITEMS 20
#include <iostream>
#include <string>
#include <limits>
#include <fstream>


class Item{
private:
    int itemNumber;
    std::string itemCategory;
    std::string itemDescription;
    double itemPrice;

public:
    Item();

    //setter function
    void setItemDetails();
    void editItemDetails();

    //getter function
    void printItemDetails();

    //save to file
    void save(std::ofstream &outfile);
};
#endif //RESTAURANTMENU_ITEMS_H

Файл реализации:

    #include "item.h"

//constructor
Item::Item(){
    itemNumber = 0;
    itemCategory = "Item not categorised.";
    itemDescription = "No description written.";
    itemPrice = 0.0;
}

//setter functions
void Item::setItemDetails() {
    int choice;

    static int counter = 1;
    itemNumber = counter++;

    std::string copyCategory;
    std::cout << "What category is this item?" << std::endl;
    std::cout << "1. Meat Dish\n2. Fish Dish\n"
                 "3. Vegetarian Dish\n4. Drink\n";
    std::cin >> choice;
    switch (choice) {
        case 1:
            itemCategory = "Meat";
            break;
        case 2:
            itemCategory = "Fish";
            break;
        case 3:
            itemCategory = "Vegetarian";
            break;
        case 4:
            itemCategory = "Drink";
            break;
        default:
            std::cout << "Error. Please enter a number between 1-4: " << std::endl;
            std::cin >> choice;
        }

            std::cout << "Please enter a short description: " << std::endl;
            std::cin.ignore(100, '\n');
            std::getline(std::cin, itemDescription);

            std::cout << "Please set the price: " << std::endl;
            std::cout << "£";
            if (!(std::cin >> itemPrice)) {
                std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
                std::cout << "Error. Please enter a number: ";
            }
}

void Item::editItemDetails() {
    int choice;

    std::string copyCategory;
    std::cout << "What category is this item?" << std::endl;
    std::cout << "1. Meat Dish\n2. Fish Dish\n"
                 "3. Vegetarian Dish\n4. Drink\n";
    std::cin >> choice;
    switch (choice) {
        case 1:
            itemCategory = "Meat";
            break;
        case 2:
            itemCategory = "Fish";
            break;
        case 3:
            itemCategory = "Vegetarian";
            break;
        case 4:
            itemCategory = "Drink";
            break;
        default:
            std::cout << "Error. Please enter a number between 1-4: " << std::endl;
            std::cin >> choice;
    }

    std::cout << "Please enter a short description: " << std::endl;
    std::cin >> itemDescription;
    //std::cin.ignore(100, '\n');
    //std::getline(std::cin, itemDescription);

    std::cout << "Please set the price: " << std::endl;
    std::cout << "£";
    //if (!(std::cin >> itemPrice)) {
        //std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        //std::cout << "Error. Please enter a number: ";
        std::cin >> itemPrice;
    //}
}

//getter functions
void Item::printItemDetails(){
    std::cout << "\nItem Number: " << itemNumber << "| Category: "
    << itemCategory << "| Description: " << itemDescription << "| Price: £" << itemPrice;
}

//save to file
void Item::save(std::ofstream &outfile) {
    outfile << "\nItem Number: " << itemNumber << "| Category: "
              << itemCategory << "| Description: " << itemDescription << "| Price: £" << itemPrice;
}

main. cpp

    #include <iostream>
#include "item.h"

int main() {
    Item newDish[MAX_ITEMS];
    bool exit = false;
    int choice;
    int count = 0;
    std::ofstream saveFile;
    saveFile.open("menu.txt", std::ios::in | std::ios::out);

    while (!exit) {
        std::cout << "Menu Creation Terminal\n\n" << std::endl;
        std::cout << "\tWelcome to Wrapid™ Restaurants\n\n\t\tMenu Creation Terminal\n\n" << std::endl;
        std::cout << "1. Add a new dish\n2. Edit Current Menu\n3. Quit\n" << std::endl;
        std::cout << "Please select an option: ";
        std::cin >> choice;

        switch (choice) {
            case 1: {
                int option = true;
                int i;


                //create items
                std::cout << "Item Creation Menu";
                for (i = 0; i < MAX_ITEMS; i++) {
                    count += 1;
                    std::cout << "\n\nItem number: " << i+1 << "\n\n";
                    newDish[i].setItemDetails();
                    newDish[i].save(saveFile);


                    std::cout << "Would you like to add another item?" << std::endl;
                    std::cout << "1. Yes\n2. No" << std::endl;
                    std::cin >> option;
                    if (option == 2) {
                        break;
                    }
                    std::cout << "You have added the following items: " << std::endl;
                    newDish[i].printItemDetails();
                }
            }
                break;
            case 2: {
                int editOpt;
                int i;

                //edit items
                std::cout << "Edit Current Menu\n\n" << std::endl;
                for (i = 0; i < count; i++) {
                    newDish[i].printItemDetails();
                }
                std::cout << "\n\nPlease enter the item number of the item you would like to edit: " << std::endl;
                std::cin >> editOpt;
                while(editOpt > 20) { std::cout << "Error. Limited to 20 items.\n"
                                                   "Please try again: "; std::cin >> editOpt; }
                i = editOpt-1;
                newDish[i].editItemDetails();
                newDish[i].save(saveFile);
            }
                break;
            case 3: {
                std::cout << "Thanks for using this terminal. Have a nice day." << std::endl;
                exit = true;
            }
            break;
            default: {
                std::cout << "Error. Invalid selection. Please select a valid option: " << std::endl;
                std::cin >> choice;
            }
        }
    }
    saveFile.close();
    return 0;
}

1 Ответ

0 голосов
/ 10 апреля 2020

измените эту строку в главном, потому что каждый раз, когда вы перезаписываете файл, всегда открывайте файл в режиме добавления

std::ofstream saveFile;
saveFile.open("menu.txt", std::ios::in | std::ios::out | std::ios_base::app);

Надеюсь, это решит вашу проблему

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...