简体   繁体   中英

How do I read the sizes of a matrix in a text file, C

I have matrices in a text file in the format:

1 2 4
2 5 6
7 8 9

5 6 7 8
6 7 8 9
7 8 9 0

These are just two arbitary matrices and they are seperated by an empty line. I know how to read in from a text file into multidimensional arrays in C but I am a little confused on how to get the number of rows and columns for the matrices in the given format. They can be of different lengths each time. How do I infer the number of rows and columns?

This may be a less than elegant solution, but it solves the problem.

Implement your own, special function that reads characters from the screen. Once it notices an end of line, \\n , interpret that as a line. Something like this:

int readInteger(char *endCharacter) {
  char input;
  int integer;
  integer = 0;
  input = getchar();
  while (input != ' ' && input != '\n') {
    integer += (int)input - '0';
    integer *= 10;
    input = getchar();
  }
  *endCharacter = input;
  return integer;
}

int *integerRowFromInput() {
  int *row;
  int size;
  char endCharacter;
  row = malloc(sizeof(int));
  row[0] = readInteger(&endCharacter);
  size = 1;
  while (endCharacter != '\n') {
    size++;
    row = realloc(size * sizeof(int));
    row[size - 1] = readInteger(&endCharacter);
  }
  return row;
}

Of course, this code needs adaption for further use, but this might be an approach for getting the input without having gotten specified what the dimensions of the matrices are.

If you cannot modify the file format to include the size beforehand, you have no other choice than to read lines until you find an empty one. Similarly, you'll need to parse at least one line completely to find out how many columns the matrix has.

You have two choices to read the matrix then: either you read the lines into a buffer with enough bytes to cover the largest matrices, or you go back to the first line of the matrix and allocate the matrix array according to the size information you just obtained.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM