首页 > 解决方案 > 文本文件中矩阵的维度

问题描述

我想以形式评估方阵的维度

-2  2 -3
-1  1  3 
 2  0 -1

所以在这种情况下n = 3,我的代码可以读取所有整数的数量,但我想停在第一行并获取前3个数字..

#include <stdio.h>

int main(){
  int temp;
  int n = 0;

  FILE *file = fopen("matrix","r");

  if(file == NULL){
    printf("Could not open specified file");
    return 1;
  }
  while(fscanf(file,"%d",&temp) == 1){
    n++;
  }  

  fclose(file);

  printf("%d",n);
  return 0;
}

标签: c

解决方案


我可能有一些过于复杂的事情,但如果我必须这样做,我会这样做。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE* file_in = fopen("mat1", "r");

    char c;
    int temp;
    int n = 0;
    if (file_in)
    {
        // you get the characters one by one and check if
        // if it is an end of line character or EOF
        while ((c = (char)fgetc(file_in)) != '\n' && c != EOF)
        {
            // if it wasn't, you put it back to the stream
            ungetc(c, file_in);
            // scan your number
            fscanf(file_in, "%d", &temp);
            n++;
        }

        fclose(file_in);
    }
    else
    {
        fprintf(stderr, "Could not open specified file.\n");
        return 1;
    }

    printf("Number of numbers: %d\n", n);

    return 0;
}

也许这回答了你的问题......但是我认为它会更简单,(如上所述)看fgets. 之后你甚至不需要sscanf读取行,因为如果你的矩阵实际上是一个方阵,那么你得到的行数就是你的矩阵的维数。干杯!


推荐阅读