使用空格分隔符将文件读入C数组

时间:2015-09-08 01:36:24

标签: c arrays file

我目前正在尝试读取由空格分隔的文件。我已经能够让它逐行读取,但现在我需要用空格分隔它,这样我就可以把它放到一个数组中。如何将它分成阵列?

#include <stdio.h>
int main ( void )
{
    int data_array[3];
    int num1;
    int num2;
    int num3;

    static const char data[] = "data.txt";
    FILE *file = fopen ( data, "r" );
    if ( file == NULL )
    {
        printf("An error occured reading the file. Check to make sure file is not locked.");
    }
    else
    {
        char line [ 1024 ]; // hopefully each line does not exceed 1024 chars
        while ( fgets ( line, sizeof line, file ) != NULL ) // reads each line
        {
            // reads each number into an array
            scanf("%d %d %d", num1, num2, num3);
            data_array[0] = num1;
            data_array[1] = num2;
            data_array[2] = num3;
        }
        fclose ( file ); // closes file
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

scanf("%d %d %d", num1, num2, num3);

由于您已经将文件中的字符读取到line,因此您应将其更改为sscanf()

sscanf(line, "%d %d %d", &num1, &num2, &num3);