c - 如何使用 fscanf 在 C 中读取 double

标签 c scanf

<分区>

我目前正在编写一个程序,该程序接收未知数量的 double ,每个 double 来自文本文件中的每行。它应该将这些元素读入一个数组,但它不起作用。我的打印循环有效,但它只打印零。在来这里之前,我已经尝试了很多东西并查阅了很多东西。这是我的代码。

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

int main()
{
    //Open an file to read from
    FILE *file;
    file = fopen("data.txt","r");
    if (file == NULL)
    {
        printf("File not found.");
        return -1;
    }

    //Count the number of lines in the input file
    int numLines = 0; //CHANGE TO 1 ???
    int ch;
    do
    {
        ch = fgetc(file);
        if (ch == '\n')
            numLines++;
    } while (ch != EOF);

    //Put all of the data read into an array;
    double input[numLines];
    int i = 0;
    while ((fscanf(file, "%lf\n", &input[i])) == 1)
        i++;

    //Close the file
    fclose(file);

    //Test printing elements of array
    for (i = 0; i < numLines; i++)
        printf("%lf\n", input[i]);

    return 0;
}

最佳答案

OP 对 fscanf() 的测试结果很好,除了代码没有检查文件中的数字是否过多。

while ((fscanf(file, "%lf\n", &input[i])) == 1)
    i++;

然后代码忽略 i 的最后一个值,而是打印 numLines 次,即使成功扫描的次数更少。

for (i = 0; i < numLines; i++)
    printf("%lf\n", input[i]);

结束代码应该是

while (i < numLines && (fscanf(file, "%lf\n", &input[i])) == 1)
    i++;
for (j = 0; j < i; j++)
    printf("%lf\n", input[j]);

这将打印 0 行!该文件需要为第二遍重置。 @paulr

rewind(file);
while (i < numLines && (fscanf(file, "%lf\n", &input[i])) == 1)
  ...

另一个问题是假设 '\n' 的计数与数字的计数相同。如果每行有多个数字或最后一行有数字但没有 '\n',这很容易被愚弄。

一个简单的解决方法,使 input[] 1 变大,并使用实际扫描成功计数作为要打印的数字计数。更健壮的代码将使用 fgets() 一次读取 1 行,并包括额外的错误检查。

关于c - 如何使用 fscanf 在 C 中读取 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43286609/

相关文章:

将文本文件复制到数组

c++ - LNK2019 : unresolved external symbol -- Implicit DLL

c - 我如何在 ansi c windows lib 中的线程中传递参数也可以使用?

c - 如何知道用户是否在输入窗口中输入了多个字符

c - 如何 sscanf 以确保缓冲区正是我想要的?

c - 如何在 HDF5 中写入固定长度的字符串?

c - 结构体指针中的 "dereferencing pointer to incomplete type”

c - 如何将扫描值推送到 C 中的堆栈?

c - 使用 scanf 读取字符串作为输入

c - 线性搜索保存到文件的结构中的元素