简体   繁体   English

如何读取文本文件中矩阵的大小,C

[英]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.我知道如何从文本文件读入 C 中的多维数组,但我对如何获取给定格式的矩阵的行数和列数感到有些困惑。 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.一旦它注意到行尾\\n ,就将其解释为一行。 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.然后您有两种选择来读取矩阵:要么将行读入具有足够字节的缓冲区以覆盖最大的矩阵,要么返回到矩阵的第一行并根据您刚刚的大小信息分配矩阵数组获得。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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