'i want to print no in 2d array by taking inputs but it will give wrong output

i am using vectors and i want to print same output as per the input by using the exact method in the code trying to using 2 d vectors

//the cause of the error is the while j loop part i mark it in the code

#include <bits/stdc++.h>
using namespace std;

// vector<int> dynamicArray(int *n,int *q)
// {
// }

int main()
{
    int n, size, a;
    cin >> n >> size;
    vector<vector<int> > q;
    // vector<int>q;
    vector<int> q1;
    for (int i = 0; i < size; i++) {
        int j = 3;
        // here error occurs
        while (j > 1) {
            cin >> a;
            q1.push_back(a);
            j--;
        }
        q.push_back(q1);
    }

    for (int i = 0; i < q.size(); i++) {
        for (int j = 0; j < 3; j++) {
            cout << q[i][j];
        }
        cout << endl;
    }

    return 0;
}

// here are the inputs

2 5
1 0 5
1 1 7
1 0 3
2 1 0
2 1 1

expected output

1 0 5
1 1 7
1 0 3
2 1 0
2 1 1

//here are the output

resulting output

100
105
105
105
105
c++


Solution 1:[1]

I think that your code has 2 bugs in it. Firstly, you are not clearing vector q1 after every processed line, thus your code is pushing to q vector with the same prefix of values every time and that's why the output is the same line repeated multiple times.

Secondly, i think that you are trying to read 3 elements in every line but currently because of condition while(j > 1) you are reading only 2 elements. Try to change it to while(j > 0).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michal Kardas