как прочитать матрицу из входного потока в C ++? - PullRequest
0 голосов
/ 18 марта 2020

У меня есть вход от isstream

1 2
3 4
5 6

Я хотел бы заполнить это из-за перегрузки isstream оператором >>

вход будет выглядеть как

Matrix m;
string input = "1 2 \n 3 4\n 5 6\n";
istringstream ss(input);
ss >> m;

как мне реализовать оператор >> для разбора матрицы из isstream?

Я пробовал приведенный ниже код, но, похоже, вызов peek игнорирует новую строку

std::istream& operator>>(std::istream& is, Matrix& s)
{
    vector<vector<int>> elements;

    int n;

    while (!is.eof())
    {
        vector<int> row;
        while ((is.peek() != '\n') && (is >> n))
        {
            row.push_back(n);
        }
        is.ignore(numeric_limits<streamsize>::max(), '\n');
        elements.push_back(row);
    }

    return is;
}

1 Ответ

1 голос
/ 18 марта 2020

Самый простой способ - анализировать одну строку за раз:

std::istream& operator>>(std::istream& is, Matrix& s)
{
    std::vector<std::vector<int>> elements;
    for (std::string line; std::getline(is, line);) {
        std::istringstream line_iss{line};
        std::vector<int> row(std::istream_iterator<int>{line_iss},
                             std::istream_iterator<int>{});
        elements.push_back(std::move(row));
    }
    s.set(elements); // dump elements into s (adapt according to the interface of Matrix)
    return is;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...