Функция для считывания последовательностей из текстового файла

Рейтинг: 0Ответов: 1Опубликовано: 11.06.2023

Не работает последняя функция считывания последовательности из текстового файла

istringstream iss(line);
        int num;
        while (iss >> num) {
            array->add(num);
            list->add(num);
        }

Подписывается красным при объявлении iss и >> в цикле. Про iss пишет, что недопустимый неполный тип, а про >> что отсутствует оператор.

Весь код для полноты картины functions.h

#pragma once

#include <iostream>
#include <memory>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

class DynamicArray {

private:
    void resize();

    unique_ptr<int[]> data_;
    int size_;
    int capacity_;

public:
    DynamicArray();

    ~DynamicArray() {}

    void add(int element);

    void remove(int index);

    int get(int index) const;

    void set(int index, int element);

    int size() const;

    int capacity() const;
};

template<typename T>
class Node {
private:
    T value_;
    unique_ptr<Node<T>> next_;
public:
    Node(T value, unique_ptr<Node<T>> next)
        : value_{ move(value) }, next_{ move(next) } {}
    T get_value() const {
        return value_;
    }

    const Node<T>* get_next() const {
        return next_.get();
    }

    void set_next(unique_ptr<Node<T>> next) {
        next_ = move(next);
    }
};

template<typename T>
class LinkedList {
public:
    LinkedList() : size_{ 0 } {}

    ~LinkedList() {}

    void add(T element) {
        if (head_ == nullptr) {
            head_ = make_unique<Node<T>>(move(element), nullptr);
        }
        else {
            Node<T>* current = head_.get();
            while (current->get_next() != nullptr) {
                current = current->get_next();
            }
            unique_ptr<Node<T>> newNode = make_unique<Node<T>>(move(element), nullptr);
            current->set_next(move(newNode));
        }
        size_++;
    }

    void remove(int index) {
        if (index < 0 || index >= size_) {
            return;
        }

        if (index == 0) {
            head_ = move(head_->get_next());
        }
        else {
            Node<T>* current = head_.get();
            for (int i = 0; i < index - 1; i++) {
                current = current->get_next();
            }
            current->set_next(move(current->get_next()->get_next()));
        }
        size_--;
    }

    T& get(int index) {
        if (index < 0 || index >= size_) {
            throw out_of_range{ "Index out of range" };
        }

        Node<T>* current = head_.get();
        for (int i = 0; i < index; i++) {
            current = current->get_next();
        }
        return current->get_value();
    }

    void set(int index, T element) {
        if (index < 0 || index >= size_) {
            return;
        }

        Node<T>* current = head_.get();
        for (int i = 0; i < index; i++) {
            current = current->get_next();
        }
        current->get_value() = move(element);
    }

    int size() const {
        return size_;
    }

    const Node<T>* begin() const {
        return head_.get();
    }

    const Node<T>* end() const {
        return nullptr;
    }

private:
    unique_ptr<Node<T>> head_;
    int size_;
};

// Функция для считывания последовательностей из текстового файла
void read_sequences(const string& file_name, vector<unique_ptr<DynamicArray>>& arrays,
    vector<unique_ptr<LinkedList<int>>>& lists) {
    ifstream file(file_name);
    if (!file.is_open()) {
        cerr << "Failed to open file " << file_name << '\n';
        return;
    }

    string line;
    while (getline(file, line)) {

        unique_ptr<DynamicArray> array = make_unique<DynamicArray>();
        unique_ptr<LinkedList<int>> list = make_unique<LinkedList<int>>();

        istringstream iss(line);
        int num;
        while (iss >> num) {
            array->add(num);
            list->add(num);
        }

        // Добавляем объекты в векторы
        arrays.push_back(move(array));
        lists.push_back(move(list));
    }
    file.close();
}

Вот сама задача на всякий случай: Дан текстовый файл, содержащий последовательности целых чисел. Каждая последовательность начинается с новой строки, элементы разделяются пробелами. Вывести последовательности в порядке возрастания количества элементов. Использовать один проход по файлу

functions.cpp

#include "functions.h"

DynamicArray::DynamicArray() : size_{ 0 }, capacity_{ 5 } {
    data_ = make_unique<int[]>(capacity_);
}

void DynamicArray::add(int element)
{
    if (size_ >= capacity_) {
        resize();
    }

    data_[size_] = element;
    size_++;
}

void DynamicArray::remove(int index)
{
    if (index < 0 || index >= size_) {
        return;
    }

    for (int i = index; i < size_ - 1; i++) {
        data_[i] = data_[i + 1];
    }

    size_--;
}

int DynamicArray::get(int index) const
{
    if (index < 0 || index >= size_) {
        return -1;
    }

    return data_[index];
}

void DynamicArray::set(int index, int element)
{
    if (index < 0 || index >= size_) {
        return;
    }

    data_[index] = element;
}

int DynamicArray::size() const
{
    return size_;
}

int DynamicArray::capacity() const
{
    return capacity_;
}

void DynamicArray::resize()
{
    capacity_ *= 2;
    std::unique_ptr<int[]> newData = std::make_unique<int[]>(capacity_);
    for (int i = 0; i < size_; i++) {
        newData[i] = data_[i];
    }
    data_ = std::move(newData);
}

Ответы

▲ 0

Зачем так сложно? Используйте std::vector. Например:

std::vector<std::string> array;
std::ifstream file("имя файла");

while(file)
{
    std::string cache;
    if (file.eof()) break;
    getline(file, cache);
    array.push_back(cache); // Записываем в array строку
}
// Теперь в array есть все строчки из файла

Получили массив array со всеми строчками из файла. Далее разделяем каждую строчку на числа.

std::string cache;
std::vector<int> nums;
for (std::string strNums : array)
{
    for (char x : strNums)
    {
        if (x == ' ') {
            nums.push_back(stoi(cache));
        }
        else {
            cache += x;
        }
    }
    cache = "";
}