简体   繁体   English

fscanf()不想在读取前两个值之后读取值

[英]fscanf() doesn't want to read values after the first two are read

Basically, I'm reading a bunch of values from a text file, which has them in the following layout: 基本上,我从文本文件中读取了一堆值,这些值在以下布局中:

4 1 1 2 3 4

But the following block of code doesn't want to read the double type value following the first two int type values: 但是以下代码块不想读取前两个int类型值之后的double类型值:

int matrix_read(struct matrep *mat, const char *filename)
{
    FILE *fptr;
    unsigned m, n;
    double *ptr = NULL;
    int i, j;
    double x;
    if ((fptr = fopen(filename, "r")) == NULL)
    {
        fprintf(stderr, "Cannot Open File %s\n", filename);
        return -1;
    }
    if(fscanf(fptr, "%u", &m) != 1)
    {
        fprintf(stderr, "Failed to read number of rows\n");
        return -1;
    }
    if(fscanf(fptr, "%u", &n) != 1)
    {
         fprintf(stderr, "Failed to read number of columns\n");
        return -1;
    }

    mat->matrix = (double *)malloc(sizeof(double) * m * n);
    if (mat->matrix == 0)
    {
        fprintf(stderr, "Failed to allocate %d*%d matrix\n", m, n);
        return -1;
    }
    ptr = mat->matrix;

    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            double x;
            if (fscanf(fptr, "%f", &x) != 1)
            {
                fprintf(stderr, "Failed to read element matrix[%d,%d]\n", i, j);
                free(mat->matrix);
                mat->matrix = 0;
                mat->cols = 0;
                mat->rows = 0;
                return -1;
            }
            *ptr++ = x;//Here it reads nothing, it just gives me: -9.2559604281615349e+061
        }
    }
    fclose(fptr);
    mat->cols = m;
    mat->rows = n;

    return 0;  // Success   
}

What am I doing wrong? 我究竟做错了什么?

fscanf(fptr, "%f", &x)

For scanning double s, you need the %lf format. 要扫描double s,您需要%lf格式。 %f scans a float . %f扫描一个float Using the wrong format invokes undefined behaviour, what probably happens is that the scanned value is converted to a float and then stored in the first four bytes of the pointed-to double . 使用错误的格式会调用未定义的行为,可能发生的情况是将扫描的值转换为float ,然后存储在指向double的前四个字节中。

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

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