Files

I don't know how to retrieve files for 2D arrays. Help is really appreciated.

Write a program that creates a two-dimensional array, reads data from file numbers.txt, assigns the values to the array items, and process them. The program should have the following functions: 
I just need help writing a code that retrieves the numbers and puts them into an array and processes them.
I just need the code, not inputting this info into the code but retrieving them.

47 23 61 32

89 12 45 5

65 62 34 27

36 74 11 23

12 66 28 57

25 65 95 45

17 88 91 64

83 31 10 7

62 30 16 18

10 29 64 7

87 56 42 95

62 21 34 4

in c++
if there aren't any empty lines between each row: (I say this because here, they are, but if there aren't any on the file)

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
#include<fstream>
#include<iostream>
#include<string>
#include<sstream>

using namespace std;

ifstream fin("input.txt");

int arr[100][100];

void getInput(){
string currLineNum="";         //string to store the numbers 
int row = 0;
while (getline(fin, currLineNum)){         //getline from ifstream
    istringstream getNums(currLineNum);  //make an istringstream so you can read from string
    int column = 0;
    int numInput;
    while (getNums>>numInput){       //read input
        arr[row][column] = numInput;
        column++;                          //counter for column
    }
    row++;                        //counter for row
    currLineNum = "";          //reinitialize currLineNum
}
}

int main(){
getInput();
for (int i=0; i<12; i++){
    for (int j=0; j<4; j++){
        cout<<arr[i][j]<<" ";
    }
    cout<<endl;
}
}


if there are any empty lines between each row, some rows would be missed. If that is so, just put anoter getline() at the end of the first while to "clean" the rubbish.
Last edited on
What code have you done so far? Since there is no code to help you with, below are the tutorials that could help.

Below is the tutorial of how to read files:
http://www.cplusplus.com/doc/tutorial/files/

Below is the tutorial of arrays
http://www.cplusplus.com/doc/tutorial/arrays/
Topic archived. No new replies allowed.