【问题标题】:Issue with fscanf reading 2-d array of doubles from text filefscanf 从文本文件中读取二维双精度数组的问题
【发布时间】:2013-01-09 13:47:12
【问题描述】:

我在 C 中使用 fscanf 时遇到了一些问题。我已将一个随机矩阵写入一个文件,现在正尝试将文本文件中的数据读入另一个矩阵。它似乎可以很好地读取行数和列数,但它为数据值返回零。我完全被卡住了,所以任何帮助将不胜感激!

我的 MATRIX 结构被声明为

typedef struct matrep {
      unsigned rows, columns;
      double *data;
      }MATRIX;

我的文件如下所示:

rows = 5, columns = 10

  -99.75  12.72  -61.34  61.75  17.00  -4.03  -29.94  79.19  64.57  49.32
  -65.18  71.79  42.10   2.71  -39.20  -97.00  -81.72  -27.11  -70.54  -66.82
  97.71  -10.86  -76.18  -99.07  -98.22  -24.42   6.33  14.24  20.35  21.43
  -66.75  32.61  -9.84  -29.58  -88.59  21.54  56.66  60.52   3.98  -39.61
  75.19  45.34  91.18  85.14   7.87  -71.53  -7.58  -52.93  72.45  -58.08

这是我的matrix_read 函数:

MATRIX matrix_read(char file_name[15])
{
int i,j, m, n;
MATRIX B;
FILE *filep;
double *ptr = NULL;
double x;

if((filep = fopen("matrixA.txt", "r"))==NULL)
{
printf("\nFailed to open File.\n");
        }
if(fscanf(filep, "\n\nrows = %u, columns = %u\n\n", &m, &n) != 2)
{
    printf( "Failed to read dimensions\n");
    B.data = 0;
    B.columns = 0;
    B.rows = 0;
}
B.data = (double *)malloc(B.columns*B.rows*sizeof(double));
if(B.data ==0)
   {
    printf("Failed to allocate memory");
    }

fscanf(filep,"\n\nrows = %u, columns = %u\n\n",&m,&n);
rewind(filep);

ptr = B.data;

for (i = 0; i < m; i++)
{
    for (j = 0; j < n; j++)
    {

        if (fscanf(filep, "  %5.2lf", &x) != 1)
       {
           printf("Failed to read element [ %d,%d ]\n", i, j);
           B.data = 0;
           B.columns = 0;
           B.rows = 0;
        }
        printf("%5.2lf\t", x);
        *ptr++ = x; 
        }
      }

 B.rows=m;
 B.columns=n;
 return B;
 fclose(filep);
 free(ptr);
 }

谢谢!

【问题讨论】:

    标签: c file matrix scanf


    【解决方案1】:

    您有几个问题,其中一个是@simonc 指出的,另一个可能是: 读取 filep 中的列和行后倒带

    rewind() 将与流关联的位置指示器设置为文件的开头,您正在再次阅读rows = 5, columns = 10

    最后:

    B.data = (double *)malloc(B.columns*B.rows*sizeof(double)); /* Don't cast malloc */
    if(B.data ==0)
    {
      printf("Failed to allocate memory");
      /* You have to return or exit here */
    }
    

    【讨论】:

      【解决方案2】:

      Alter Mann所指,去掉第二个

      fscanf(filep,"\n\nrows = %u, columns = %u\n\n",&m,&n);
      

      还有

      rewind(filep);
      

      此外," %5.2lf" 不是有效的 scanf 转换规范(您可以阅读有关此内容的手册) - 请改用 "%lf"

      【讨论】:

        猜你喜欢
        • 2020-07-11
        • 1970-01-01
        • 2015-03-29
        • 2016-06-11
        • 1970-01-01
        • 2016-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多