在C中加载文本文件中的数字

Joh*_*ohn 4 c

我想从文本文件(.txt)将已知数量的数字加载到C中的数组中.格式为:

"0,1,2,5,4"

我是C的新手,有人可以推荐一种加载文本文件的方法吗?

干杯

Ara*_*raK 5

它可以通过以下方式轻松完成fscanf:

#include <stdio.h>
int main()
{
    FILE* f = fopen("test.txt", "r");
    int number = 0;
    int sum = 0; /* the sum of numbers in the file */

    while( fscanf(f, "%d,", &number) > 0 ) // parse %d followed by ','
    {
        sum += number; // instead of sum you could put your numbers in an array
    }

    fclose(f);
}
Run Code Online (Sandbox Code Playgroud)

@pmg:当然,为什么不呢.我只是如果它是一个hw,那么给出一个完整的解决方案是一件坏事:)

#include <stdio.h>
int main()
{
    FILE* f = fopen("test.txt", "r");
    int n = 0, i = 0;
    int numbers[5]; // assuming there are only 5 numbers in the file

    while( fscanf(f, "%d,", &n) > 0 ) // parse %d followed by ','
    {
        numbers[i++] = n;
    }

    fclose(f);
}
Run Code Online (Sandbox Code Playgroud)