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

标签 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;
}

最佳答案

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

因为您已经从文件读取字符到,您应该将其更改为sscanf(),例如

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

关于c - 使用空格分隔符将文件读入 C 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32448012/

相关文章:

为 Vala 编译 gcrypt

c - 在验证回调中访问目标域(主机名)

javascript - JavaScript 中的月份数组不漂亮

javascript - 为什么 forEach 函数不执行任何循环步骤

c - 避免快速除法(倒数)

javascript - 干燥 htmlCollection 到 Array 调用

file - 上传路径似乎无效”。 Codeigniter 文件上传

java - 如何从 Apache 的 UploadedFile 类中获取 java.io.File?

java - 如何从 java.nio.Path 获取路径字符串?

c - 如何编写递归 Strrchr?