0

У меня есть queue.h, queue.cpp и main.cpp. А так же есть файл, в котором находятся 4 типа данных, написанные через пробел в одной строке и в определенной последовательности. Таких строк несколько, где меняются лишь значения данных. Одно из главных значений это первое, по которому собственно и будет происходить поиск строки.

Пример:

1 B 14 15.68
2 B 3 23.54 
1 S 5 13.2
3 B 4 9.99

Я помещаю данные из файла в очередь и уже в main.cpp начинаю с ними работать. Примечательно то, что у меня объявлено 3 объекта класса "Queue", ибо судя по первой цифре у меня есть 3 типа строк, которые могут повторяться.

Проблема в том, что при считывании и вызове например строк с первым символом 1, у меня вылетает строка с символом 2...

main.cpp

#include <iostream>
#include "queue.h"
#include <fstream>
#include <string>

int main() {
    std::fstream input;
    input.open("inventar.txt");
    int option, key, quantity;
    char type, choise;
    double price;

    Queue item1;
    Queue item2;
    Queue item3;
        

    do {
        std::cout << "i > инвентарь\n"<< "n > считать данные\n" << "s > statistika\n" << "e > exit\n" << "Ваш выбор: ";
        std::cin >> choise;
        Node* temp = new Node();
        Node* front;
        Node* rear;
        Node* n;


        switch (choise) {
        case 'i':
            std::cout << "Zadajte Vas vyber: ";
            std::cin >> option;

            if (option == 1) {
                item1.display();
            }
            else if (option == 2) {
                item2.display();
            }
            else if (option == 3) {
                item3.display();
            }
        case 'n':
            if (!input) {
                std::cout << "Chyba v nacitavani suboru!" << std::endl;
            }
            else {
                //nacitavanie zo suboru, ci ze pridanie prvkov do zoznamu
                while (!input.eof()) {
                    if (temp->key == 1) {
                        input >> key >> type >> quantity >> price;
                        temp->key = key;
                        temp->type = type;
                        temp->quantity = quantity;
                        temp->price = price;
                        item1.enqueue(key, type, quantity, price);
                    }
                    else if (temp->key == 2) {
                        input >> key >> type >> quantity >> price;
                        temp->key = key;
                        temp->type = type;
                        temp->quantity = quantity;
                        temp->price = price;
                        item2.enqueue(key, type, quantity, price);
                    }
                    else {
                        input >> key >> type >> quantity >> price;
                        temp->key = key;
                        temp->type = type;
                        temp->quantity = quantity;
                        temp->price = price;
                        item3.enqueue(key, type, quantity, price);
                    }
                }
            }
            continue;
        case 'e':
            std::cout << "Koniec programu" << std::endl;
            input.close();
            return 0;
        }
    } while (choise != 'e');
}

queue.cpp

#include "queue.h"
#include <iostream>
using namespace std;

bool Queue::isEmpty() {
    if (front == NULL && rear == NULL) {
        return true;
    }
    else {
        return false;
    }
}

void Queue::enqueue(int vKey, char vType, int vQuantity, float vPrice) {
    Node* ptr = new Node();
    ptr->key = vKey;
    ptr->type = vType;
    ptr->quantity = vQuantity;
    ptr->price = vPrice;

    ptr->next = NULL;

    if (front == NULL) {
        front = ptr;
        rear = ptr;
    }
    else {
        rear->next = ptr;
        rear = ptr;
    }
}

void Queue::dequeue() {
    if (isEmpty()) {
        cout << "Queue is Empty" << endl;
    }
    else {
        if (front == rear) {
            free(front);
            front = rear = NULL;
        }
        else {
            Node* ptr = front;
            front = front->next;
            free(ptr);
        }
    }
}

void Queue::show() {
    if (isEmpty()) {
        cout << "Queue is empty" << endl;
    }
    else {
        cout << front->key;
    }
}

void Queue::display(){
    if (isEmpty()) {
        cout << "Queue is empty" << endl;
    }
    else {
        Node* ptr = front;
        while (ptr != NULL) {
            if (ptr->key == 1) {
                //cout << key << type << quantity ....
                cout << ptr->key << " " << ptr->type << " " << ptr->quantity << " " << ptr->price << endl;
                ptr = ptr->next;
            }
            else if (ptr->key == 2) {
                cout << ptr->key << " " << ptr->type << " " << ptr->quantity << " " << ptr->price << endl;
                ptr = ptr->next;
            }
            else if (ptr->key == 3) {
                cout << ptr->key << " " << ptr->type << " " << ptr->quantity << " " << ptr->price << endl;
                ptr = ptr->next;
            }
        }
    }
}

queue.h

#pragma once
#include <iostream>

using namespace std;

struct Node {
    int key, quantity;
    char type;
    float price;
    Node* next;
};



class Queue {
public:
    Node* front = NULL;
    Node* rear = NULL;

    Queue() {
    };
    bool isEmpty();
    void enqueue(int vKey, char vType, int vQuantity, float vPrice);
    void dequeue();
    void show();
    void display();
};
8
  • Честно, вообще ничего не понятно. Приведите пример входных данных, данные которые возвращает ваша программа и данные которые вы ожидали увидеть. 21 мар 2021 в 16:29
  • @ПавелЕриков В файле у меня 4 строчки, каждая начинается с новой строки, как я описал выше. И в каждой строке есть первый символ - цифра: один, два или три . В main.cpp, через switch я сначала записываю каждую строку в очередь отдельно, а далее так же через switch я ввожу, к примеру 1 и мне должна программа выдать все строчки с данной цифрой в начале, это как ее номер. Аналогично с цифрой 2 и 3 при вызове.
    – one1three3
    21 мар 2021 в 16:41
  • То есть 1 B 14 15.68, 2 B 3 23.54, 1 S 5 13.2, 3 B 4 9.99 это 4 строчки? И все таки, что выводит программа и что вы ожидали увидеть в результате. 21 мар 2021 в 16:43
  • @ПавелЕриков Да, это строчки, каждая с нового ряда записана в файле. Вот я ввожу 1 и мне должно выдать: 1 B 14 15.68 1 S 5 13.2. То есть эти две строчки, где в начале стоит единица. Аналогично с двойкой и тройкой.
    – one1three3
    21 мар 2021 в 16:46
  • @ПавелЕриков И в принципе оно выводится, но если я задаю, мол мне нужны строки под номером 1 , а мне выдает 2 и 3, когда задаю, что мне нужен номер 2, выдает 2, здесь все нормально, но вот при номере 3 мне выдает обе строчки с номером 1
    – one1three3
    21 мар 2021 в 16:54

1 ответ 1

0

В общем вы хотели сделать так:

Считываете первую цифру и относительно неё заносите в одну из очередей.

Но изначально у вас temp->key не прочитан, и попадает под else. Считывает первую строку и вносит в 3 очередь что уже не правильно.

А далее в temp->key записана 1 от предыдущей записи и все дальше ломается.

Сначала считываете temp потом проверяете. Так же у вас куча ненужного кода было, немного уменьшил:

while (!input.eof()) {
    input >> temp->key >> temp->type >> temp->quantity >> temp->price;
    if (temp->key == 1)
        item1.enqueue(temp->key, temp->type, temp->quantity, temp->price);
    else if (temp->key == 2)
        item2.enqueue(temp->key, temp->type, temp->quantity, temp->price);
    else
        item3.enqueue(temp->key, temp->type, temp->quantity, temp->price);
}
1
  • благодарю за помощь, конечно ошибка очень глупая)
    – one1three3
    21 мар 2021 в 21:35

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.