0

I don't understand how to use fscanf in C to place data from a text file into an array and also be able to edit the text file as a user from the cli :S (complete noob here..) I tried googling but all that shows up are forums with more problems than solutions and c++ non-examples.

Any help/examples would be greatly appreciated :)

Edit: thanks for the quick responses, I seem to have forgotten to mention that I want to use a 2D array and the txt file contains integers with a space between each following element as well as a new line for each row!

Edit 2: so from what I gather I must use:

  1. Fscanf ("filename.txt", "rw")
  2. Create an array[i][j]
  3. Nested for loop for i and j
  4. How to get fscanf data into the array?? 5.printf("%d\n", &array[i][j])
user1883003
  • 57
  • 2
  • 7

2 Answers2

1

Depending on how your input data is formatted, you can do something like this to read the values on each line.

int data[MAX_X][MAX_Y];
FILE * fp = fopen("mydata.txt", "r");
int x, y, value;
// TODO: Initialize data array
while (3 == fscanf(fp, "%d %d %d\n", &x, &y, &value))
{
    if ((x >= MAX_X) || (y >= MAX_Y))
    {
        fprintf(stderr, "range error\n");
        break;
    }
    data[x][y] = value;
}

A lot of the details hinge on the format of the input data.

4bitfocus
  • 46
  • 2
  • Thanks for your response, the data are integer values i.e. 23 64 9 32 56 42 98 4 44 87 68 60 51 22 11 and so on – user1883003 Dec 07 '12 at 20:18
  • How should they be read into the 2D array? There's no indication of the target x/y indexes. Does the first belong at [0,0] then next at [0,1] and so on? Is there a fixed limit on the number of integers? I'm wondering if fscanf() is not the best method for reading in the values. – 4bitfocus Dec 12 '12 at 16:14
0

Split the problem in parts:

  1. how to read one number with fscanf
  2. how to move to next number
  3. how to iterate over lines

Then ask again separately.

Pavel Radzivilovsky
  • 18,794
  • 5
  • 57
  • 67