C - 从文件中读取大量数字

Fid*_*flo 1 c floating-point file

我有一个大数字的文件,-7.47004e-16我试图将其读入浮点数组使用

fscanf(rhs, "%f", &numbers[i]);" 
Run Code Online (Sandbox Code Playgroud)

这是一个循环.但是当我们有一个如上所述的数字时,这不起作用.

由于数量如此之大,这不起作用吗?或者这不是数字格式中"e"的原因吗?

你能推荐一些正确的方法吗?

谢谢.

注意:Numbers是一个float数组,rhs是文件名.该文件每行有一个数字,有些数字与上面的格式相同,有些数字要小得多,如-1.88493.

这是代码:

int main( int argc, char *argv[])
{
    FILE *rhs, *output;
    int niter, n, n1;
    // counters
    int i = 0, j = 0, k, m, p;

    rhs = fopen(argv[1], "r");
    // ab+ opens file for writting and creates the file if need be
    output = fopen(argv[2], "ab+");
    niter = atoi(argv[3]);

    // check if files open up or not, if not exit.
    if((rhs == NULL) || (output == NULL))
    {
        printf("Error Opening files.\n");
        exit(1);
    }

    // read in N
    fscanf(rhs, "%d", &n);

    // initialize n1
    n1 = n + 1;

    // generate array to hold values from rhs file
    long double *numbers = (long double *)malloc(sizeof(long double) * ((n1)*(n1)));
    long double *y = (long double *)malloc(sizeof(long double) * ((n1)*(n1)));
    long double *f = (long double *)malloc(sizeof(long double) * ((n1)*(n1)));
    long double *yp = (long double *)malloc(sizeof(long double) * ((n1)*(n1)));

    // get numbers and store into array
    for(i = 0; i <= n; i++)
    {
        for(j = 0; j <= n; j++)
        {
            fscanf(rhs, "%Lf", &numbers[i]);
            printf("i = %d, number = %Lf\n", i, numbers[i]);
        }
    }

    for(k = 0; k < niter; k++)
    {
        smooth(n, y, yp, f);
    }

    fclose(rhs);
    free(numbers);
    free(y);
    free(f);
    free(yp);

    return 0;
Run Code Online (Sandbox Code Playgroud)

}

Jon*_*ler 5

SSCCE(简短,自包含,正确的例子)

#include <stdio.h>

int main(void)
{
    FILE *rhs = stdin;
    int i = 0;
    float numbers[2];

    if (fscanf(rhs, "%f", &numbers[i]) != 1)
        printf("Failed to convert anything\n");
    else
        printf("Got: %13.6e\n", numbers[i]);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

示例运行:

$ ./flt
-7.47004e-16
Got: -7.470040e-16
$
Run Code Online (Sandbox Code Playgroud)

请注意,代码检查转换是否成功; 您应该始终这样做,并且正确的测试如下所示 - 您是否获得了正确的成功转换次数.如果不进入EOF,您可能无法进行转换,因此针对EOF的测试不正确.