array to vector
Jul 23, 2014 at 8:18pm UTC
Last night, I learned how to build a 2d array that holds variables from a text file. Today, I am learning how to make that array part of a vector.
This is my code so far.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
int sheet[5][8];
ifstream fin;
fin.open("scores.txt" );
int num;
fin >> num;
// put scores in array
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 8; j++)
{
fin >> sheet[i][j];
}
}
// declare array in vector
vector<vector<int >> score(sheet, sheet + 36);
for (unsigned int x = 0; x != score.size(); x++)
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 8; j++)
{
cout << score.at(x) << " " ; // output array
}
}
}
return 0;
}
I've tried many different ways, but this is what I'm thinking along the lines of. Any suggestions while I figure this out would be great.
Jul 23, 2014 at 9:59pm UTC
SOLVED:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
ifstream fin;
fin.open("scores.txt" );
int sheet[5][8];
typedef vector<int > one_d;
vector<one_d> two_d;
for (int i = 0; i < 5; i++)
{
two_d.push_back(one_d());
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 8; j++)
{
fin >> sheet[i][j];
two_d[i].push_back(sheet[i][j]);
cout << two_d[i][j] << " " ;
}
cout << endl;
}
return 0;
}
Last edited on Jul 23, 2014 at 10:01pm UTC
Jul 23, 2014 at 10:05pm UTC
I have 36 numbers, and I want 5 rows. This makes four extra empty spaces with random characters and numbers. I've been trying to find out a way to limit the output to 36 while still having the same amount of rows and columns. Any suggestions?
Topic archived. No new replies allowed.