1

我正在编写一个程序,该程序从 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

关于如何将数字拉入正确数组的任何想法?

4

2 回答 2

0

这是一个解决方案:

#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;
}
于 2013-04-05T22:21:58.053 回答
0

根据您的问题,要读取数据,必须修改第一个循环

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

并将数据打印为单独的数组

printf("\nStarting Bids:\t");
for (i = 0; i < cars; i++) {
    printf("%d\t", START_BID[i]);
}

printf("\nMinimum Increase:\t");
for (i = 0; i < cars; i++) {
  printf("%d\t", MIN_INCREASE[i]);
}

printf("\n");

有了这个输出控制台看起来像

Starting Bids:  50      250     5       500     300
Minimum Increase:       40      140     6       50      200
于 2013-04-05T22:26:15.177 回答