【问题标题】:fscanf does not read in correct doubles from file for multidimensional matrixfscanf 没有从多维矩阵的文件中读取正确的双精度数
【发布时间】:2017-11-10 05:26:02
【问题描述】:

我正在尝试使用fscanf 从文本文件中读取 NxN 矩阵和 1xN 矩阵的数字。我知道这个问题以前在这里被问过,但我已经尝试了解决方案,但根本无法理解为什么我的方法不起作用。 NxN 矩阵为:

1 1 1
3 1 0
-1 0 1

1xN 矩阵为:

6 
11 
-2

行中的数字用一个空格分隔,列中用\n 分隔。这是我的代码:

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

int countlines(FILE *f);
void reduce_mat(double **matrix, double *vector, int row, int column);
void swapping(double **matrix, double *vector, int row, int column);
int main()
{
  FILE *f1=fopen("matrix.txt","r");
  FILE *f2=fopen("vector.txt","r");
  int dim_matrix=countlines(f1);
  int dim_vector=countlines(f2);

  //allocate memory for matrix and vector
  double **Mat_A=(double **) malloc(dim_matrix*sizeof(double));
  for(int j=0; j<dim_matrix; j++)
    Mat_A[j]=(double *) malloc(dim_matrix*sizeof(double));

  double *Vec_B=(double *) malloc(dim_vector*sizeof(double));

  //read in numbers from file
  for(int i=0; i<dim_matrix; i++)
  for(int j=0; j<dim_matrix; j++)
  {
    fscanf(f1,"%lf",&Mat_A[i][j]);
    printf("Mat_A[%d][%d]=%lf\n",i,j,Mat_A[i][j]);
  }
  for(int k=0; k<dim_vector; k++)
  {
    fscanf(f2, "%lf", &Vec_B[k]);
    printf("Vec_B[%d]=%lf\n",k,Vec_B[k]);
  }

 int countlines(FILE *f)
 {
 //check if file exists
  if (f==NULL)
  {
    printf("File does not exist");
    return 0;
  }
  int count=0; //intialize the count
  char c; //place to store characters from file
  for (c=getc(f); c!=EOF; c=getc(f))
  {
    if (c=='\n')
    {
      count+=1;
    }
  }
  return count;
 }

它只是为每个值打印出零。我曾尝试使用"%lf%[\n]%""%lf%" 等。我根本不知道哪里出错了,因为这个实现似乎对其他人有用。

【问题讨论】:

  • 检查fopenmalloc的返回值。
  • double **Mat_A=(double **) malloc(dim_matrix*sizeof(double)); 可能是错误的大小分配。使用double **Mat_A= malloc(sizeof *Mat_A * dim_matrix); 分配正确的大小。
  • 并检查fscanf的返回值。即使它可能有效,这在语义上也是错误的:double **Mat_A=(double **) malloc(dim_matrix*sizeof(double));。你想要sizeof(double *)
  • 不要转换malloc的返回值
  • 是的,你没看错。您必须“在 j 上的 for 循环内”进行分配,以便为每个数组分配内存。但是你的教授关于转换 malloc 的返回值是错误的。在 C 中没有必要。stackoverflow.com/questions/605845/…

标签: c file matrix double scanf


【解决方案1】:

计数行读取文件并使用数据。 您必须将其倒回开头以再次读取它以读取值。 所以只需在countlines函数的末尾添加一个rewind(f)

 int countlines(FILE *f)   
 {
     //check if file exists
     if (f==NULL)
     {
         printf("File does not exist");
         return 0;
     }
     int count=0; //intialize the count
     int c; //place to store characters from file
     for (c=fgetc(f); c!=EOF; c=fgetc(f))
     {
         if ((char)c=='\n')
             count++;
     }
     rewind(f); // file is now ready to be read again  
     return count;
 }

【讨论】:

  • 修复您的char c; 错误。 fgetc 返回一个精确提升为 int 的 char,因此它可以返回一个 EOF 值。
  • This can happen。 @MFisherKDX unsigned char ;)
  • @MFisherKDX 否,值是 unsigned char 提升为 int。不是char
  • @AnittiHaapala 是的。几分钟后我明白了你的意思……明白了。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-19
  • 2013-07-25
  • 1970-01-01
  • 2011-10-13
  • 1970-01-01
  • 2016-12-26
  • 1970-01-01
相关资源
最近更新 更多