vector assignment

I tried to read a text file into 2d vector but it keeps repeating the first row
here is my code. any idea?

#include "std_lib_facilities.h"
#include <vector>
#include <fstream>
#include <ostream>
using namespace std;

int main()
{
vector<vector<int> > vec;
vector<int> temp;
int values = 0;
int height = 0;
int width = 0;

ifstream fin("input1.txt");
ofstream fout("output1.txt");

fin>>height>>width;

while(fin>>values)

temp.push_back(values);

for (int temps=0; temps<temp.size(); temps++)
{
vec.push_back(temp);
}


for (int row=0; row<height; row++)
{
for (int col=0; col<width; col++)
{
cout<<vec[row][col]<<" ";
}
cout<<endl;
}


keep_window_open();
return 0;
}


output example:
input
5(row) 3(col)
2 4 2 6 6
3 7 8 3 6
8 7 9 3 8

output
2 4 2 6 6
2 4 2 6 6
2 4 2 6 6



You have a line while(fin>>values) temp.push_back(values); which pushes all the numbers into a single vector. Then you have a for loop that pushes the same vector a bunch of times.
What you need is to have nested for loops.
1
2
3
4
5
6
7
8
9
10
for(int i = 0; i < height; i++) {
   vector<int> temp;//an actually temporary variable.
   //you could declare it outside the loop and call .clear() here instead.
   for(int j = 0; j < width; j++) {
      int val;
      fin >> val;
      temp.push_back(val);
   }
   vec.push_back(temp);
}
it's much clear now. Thanks for your help. Now i can do the rest of the assignment
Topic archived. No new replies allowed.