簡體   English   中英

正確讀取先前條目后,文件 * 正在從輸入文本文件中將零讀入“雙”變量

[英]FILE * is reading zeros into a 'double' variable from input text file after reading previous entries correctly

手頭的任務是從輸入文件“as5input.txt”中讀取值,並對這些值進行一些基本的線性計算,以便稍后將它們寫入另一個 output 文本文件。 使用“fscanf()”它成功地讀取了前兩行數據,然后在它應該讀取實際值時繼續只讀取零。

我在 fscanf 上嘗試了不同的格式,並嘗試直接讀取以查看它正在讀取的值。 我確保輸入文件中沒有可能導致問題的 '\n' 或 ' ' 字符。 我還嘗試制作一個具有相同格式的新文本文件,以確保該文件沒有任何奇怪的錯誤。 但是,它仍在讀取零。

我認為這與讀取一個 int 然后讀取一個 double 有關,但它為什么會這樣是沒有意義的。

這是我正在使用的文本文件:

as5input.txt

2.0 5.0
6
1.0 2.0 4.0 8.0 16.0 31.0

這是與之交互的程序:

as5.c

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

struct instance_struct
{
    int count;
    float m, b;
    double * x, * y;
};

typedef struct instance_struct instance;

void instance_print(instance *is, FILE * ofp)
{
    int i;

    fprintf(ofp, "  y = %f x + %f\n", is->m, is->b);

    for (i = 0; i < is -> count; i++)
    {
        fprintf(ofp, "  x: %f   y: %f\n", is->x[i], is->y[i]);
    }
}

instance * make_instance(int count, float m, float b) {
    instance * is = (instance *)malloc(sizeof(instance));
    is -> m = m;
    is -> b = b;
    is -> count = count;
    is -> x = (double *)malloc(sizeof(double) * count);
    is -> y = (double *)malloc(sizeof(double) * count);
    return is;
}

int main(void)
{
    int i, count;
    float m, b;

    FILE *ifp, *ofp;
    ifp = fopen("as5input.txt", "r");
    ofp = fopen("out.txt", "w");

    fscanf(ifp, "%f %f %d", &m, &b, &count);

    double temp;
    instance * is = make_instance(count, m, b);
    for (i = 0; i < count; i++) {
        fscanf(ifp, "%f", &temp);
        printf("%f\n", temp);
        is -> x[i] = temp;
        is -> y[i] = m * temp + b;
    }

    instance_print(is, ofp);

    fclose(ifp);
    fclose(ofp);

    return 0;
}

這是 output 文件中的內容:

出.txt

  y = 2.000000 x + 5.000000
  x: 0.000000   y: 5.000000
  x: 0.000000   y: 5.000000
  x: 0.000000   y: 5.000000
  x: 0.000000   y: 5.000000
  x: 0.000000   y: 5.000000
  x: 0.000000   y: 5.000000

這就是第 51 行的 printf 的結果:

0.000000
0.000000
0.000000
0.000000
0.000000
0.000000

我可能遺漏了一些非常簡單的東西,但它正確讀取斜率、截距和計數(m,b,count)只是很奇怪。 任何幫助或建議將不勝感激。

double temp;
instance * is = make_instance(count, m, b);
for (i = 0; i < count; i++) {
    fscanf(ifp, "%f", &temp);
    ...
}

您使用%f作為格式說明符,但傳遞的是double* ,而不是float* 增加編譯器的警告,您可能會看到這樣的警告(例如-Wall for gcc/clang):

<source>:50:27: warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat]
        fscanf(ifp, "%f", &temp);
                     ~~   ^~~~~
                     %lf

解決方案是將temp設為float或使用%lf作為格式說明符。

請注意, printf%f說明符用於double精度,因為floats作為doubles傳遞給采用可變數量 arguments 的函數。 這不適用於指針。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM