views:

539

answers:

1

I've been trying to read a txt file containing a formatted matrix (9x9) into an int array. The txt file is selected by the user using NSOpenPanel.

An example txt file:

2 7 9 1 6 2 1 1 1
9 1 3 3 4 0 6 8 5
5 3 2 9 3 8 6 7 0
6 0 9 2 5 6 4 8 0
3 2 0 4 0 5 0 6 0
4 0 5 4 0 3 9 0 0
6 4 1 3 2 5 7 2 0
6 5 7 2 1 3 0 9 3
1 0 2 7 5 1 0 0 0

I'm really new to mac programming so any help would be greatly appreciated.

A: 

You can either do it with Objectice-C using classes loke NSString and NSArray reading a complete file is just NSString *filesContent = [[NSString alloc] initWithContentsOfFile:@"file.txt"];

then you can split that array e.g at whitespace with something like NSArray rows = [filesContent componentsSeparatedByString:@"\r\n"]; then you can split the rows at whitespace.

And or you do it the old faschioned C way. Opening the file with fopen reading the file line by line splitting the line e.g. with sscanf And filling an Array int arr[9][[9];

Pseudo Code (not tested, just to give you an idea)

char buf [2048];
char *pc;
int arr[9][[9];
int i_rval;
int row[9];

File *fin = fopen("file_with_9_x_9_matrix.txt");
/* error handling */
int i = 0;
while ((pc = fgets(buf, sizeof(buf), fin)) != NULL) {
    row = arr[i];
    i_rval = sscanf("%d %d %d %d %d....", &row[0], &row[1]);
    /* error handling */
    i++;
}

Or you can mix something out of Objectice-C and C.

Friedrich