【问题标题】:Read a file into C array using space delimiter使用空格分隔符将文件读入 C 数组
【发布时间】:2015-12-03 13:27:49
【问题描述】:

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

#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;
}

【问题讨论】:

  • 对不起,我不明白你想做什么。是否要将 data_array 存储在另一个数组中?
  • 我的文件有这样一行:3 5 12 我想将这些数字中的每一个读入数组 data_array。
  • 我猜你忘记粘贴行了。
  • 您忘记在传递给 scanf 的变量之前添加 &。比如:scanf("%d %d %d", &num1, &num2, &num3);
  • 根据您想要执行的操作,您可以将fgets 调用替换为直接在file 上运行的fscanf 调用,或者如果您需要保留line同样,您可以使用sscanfline 中提取数字。

标签: c arrays file


【解决方案1】:
scanf("%d %d %d", num1, num2, num3);

由于您已经将字符从文件读取到line,您应该将其更改为sscanf() 喜欢

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    相关资源
    最近更新 更多