c - 从文件中获取数字并将它们放入数组中需要的建议

标签 c

我正在编写一个程序,从 txt 文件中获取数字并将它们放入 2 个不同的数组中。

文本文件如下所示:

    50 40
    250 140
    5 6
    500 50
    300 200

我需要将第一列中的所有数字放入一个数组中,将第二列中的所有数字放入另一个数组中。

到目前为止,这是我的代码:

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

    int main()
    {
        FILE * ifp = fopen("input2.txt","r"); //Open the input file
        int cars = 5, i , j; // Initialized cars and counters i and j
        char VIEW[20], BID[20], CLOSE[20];
        int CAR[10], START_BID[10], MIN_INCREASE[10];
        int *b; // Temp pointer to current bid
        int  *m; // Temp pointer to current array of the minimum increase

        strcpy(VIEW, "VIEW");
        strcpy(BID, "BID");
        strcpy(CLOSE, "CLOSE");

     for (i = 0; i < cars; i++) {
         b = &START_BID[i]; // Get pointer to current START_BID
         m = &MIN_INCREASE[i]; // Get pointer to array of current MIN_INCREASE
         fscanf(ifp, "%d", &b[i]);
         for (j = 0; j < cars; j++) {
             fscanf(ifp, "%d", &m[i]);
         }
     }

        printf("%d\n", START_BID);
        printf("%d\n", MIN_INCREASE);

            fclose(ifp);

        return 0;
    }

我让它打印 2 个数组的内容以查看它们是否被正确拉取。

这是我的输出:

    2686588
    2686548

关于如何将数字放入正确的数组有什么想法吗?

最佳答案

这是一个解决方案:

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

int main()
{
    FILE * ifp = fopen("file.txt","r"); //Open the input file
    int cars = 5, i , j; // Initialized cars and counters i and j
    char *view="VIEW", *bid="BID", *CLOSE="CLOSE";
    int CAR[10], START_BID[10], MIN_INCREASE[10];

    for (i = 0; i < cars; i++) 
    {
        fscanf(ifp, "%d %d", &START_BID[i],&MIN_INCREASE[i]);
    }

    for (i = 0; i < cars; i++) 
    {
        printf("%d %d\n", START_BID[i], MIN_INCREASE[i]);
    }
    fclose(ifp);
    return 0;
}

关于c - 从文件中获取数字并将它们放入数组中需要的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15844447/

相关文章:

c - 如何使用 libnetfilter_conntrack 查询 conntrack?

ceil() 仅适用于右值

c - 在保留分隔符的同时在 C 中拆分 char 数组

c - 扫描多个号码,无需扫描输入C

c - 使用 C 查找 JPG/JPEG 图像的高度和宽度

c - 如何修改此组合算法以在启用 cuda 的 gpu 上并行运行?

c - 如何在 Load Runner 中设置事务的随机选择和概率

c - 为什么需要两个括号才能在 C 中使用宏?

c++ - 将文件的每一行作为命令行参数传递给二进制文件

根据用户请求创建多个整数