0

I have an input from isstream

1 2
3 4
5 6

I would like to populate this from isstream overloading the >> operator

the input would be something like

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

how do I implement the >> operator to parse the matrix from isstream?

I have tried the code below but the peek call seems to ignoring the new line

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;
}
TrustyCoder
  • 4,749
  • 10
  • 66
  • 119
  • [Does this help?](https://stackoverflow.com/q/4421706/315052) – jxh Mar 18 '20 at 01:28
  • Why not `int a, b; while (std::cin >> a >> b) { /* add a & b to vector then to matrix */ }` If the file is formatted as indicated, there is no great need for `stringstream` unless you don't know how many columns you are dealing with beforehand. (substitute whatever file stream is being used for `std::cin`) – David C. Rankin Mar 18 '20 at 01:35
  • the matrix may be n X n and handle new line and eof. i had tried peek != 'n' and EOF could not get it right. – TrustyCoder Mar 18 '20 at 02:07
  • Note that `' \n'` isn't what you probably think it is: it's a multicharacter literal, which has an implementation-defined value. – N. Shead Mar 18 '20 at 02:22

1 Answers1

0

The simplest way is to parse one line at a time:

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;
}
L. F.
  • 19,445
  • 8
  • 48
  • 82