从文件读取到数组 - C

时间:2014-03-05 02:03:32

标签: c arrays file file-io

int main()
{

    FILE* infile1;

    int stockCode[15];
    char stockName[100];
    int stockQuantity[15];
    int stockReorder[15];
    int unitPrice[15];
    int i;

    infile1  = fopen("NUSTOCK.TXT", "r");

    while(fscanf(infile1, "%d %s %d %d %f",
         &stockCode, stockName, &stockQuantity, &stockReorder, &unitPrice) != EOF)
    {
        printf("  %3d  %-18s  %3d  %3d  %6.2f \n",
          stockCode, stockName, stockQuantity, stockReorder, unitPrice);
    }

    fclose(infile1);

}

我尝试做的是从文件中获取信息并将其存储到5个单独的数组中。但是,打印时,它只会正确打印出名称。

  

1394854864 Prune-Basket 1394854688 1394854624 0.00
  1394854864 Pear-Basket 1394854688 1394854624 0.00
  1394854864 Peach-Basket 1394854688 1394854624 0.00
  1394854864 Deluxe-Tower 1394854688 1394854624 0.00

原始文件如下所示。因此,所有数字都没有被扫描出来,我无法弄清楚为什么......

  

101 Prune-Basket 065 060 25.00
  105 Pear-Basket 048 060 30.00
  107 Peach-Basket 071 060 32.00
  202 Deluxe-Tower 054 040 45.00

2 个答案:

答案 0 :(得分:2)

我认为你想要做的是设计一个用于保存许多个人记录的结构。 每条记录都包含:

  • 名称
  • 重排序
  • UNITPRICE

你应该知道C语言中每种类型的含义。

我建议你重写这些代码:

#include <stdio.h>
#include <stdlib.h>
struct OneRecord{
    int code;
    char name[100];
    int quantity;
    int recorder;
    float unitPrice;
};

int main(){


    struct OneRecord* records = (struct OneRecord*)calloc(15, sizeof(struct OneRecord));
    int i = 0;

    FILE* infile1  = fopen("NUSTOCK.TXT", "r");
    int max=0;

    //%99s is used for max string length, because of we can protect the out of string's memory length
    while((max<15)&&(fscanf(infile1, "%d %99s %d %d %f",
                &records[i].code, records[i].name, &records[i].quantity, &records[i].recorder, &records[i].unitPrice) == 5))
    {
        i++;
        max++;
    }
    for(i=0;i<max;i++){
        printf("  %3d  %-18s  %3d  %3d  %6.2f \n",
                records[i].code,records[i].name,records[i].quantity,records[i].recorder,records[i].unitPrice);
    }

    fclose(infile1);
    free(records);
}

如何在函数或许多其他地方使用C Structure? 在C编程语言中,有不同的类型,如int,char,struct等。您可以像许多其他类型一样使用struct

void printRecords(const struct OneRecord* records, int max)
{
    int i;
    for(i=0;i<max;i++){
        printf("  %3d  %-18s  %3d  %3d  %6.2f \n",
                records[i].code,records[i].name,records[i].quantity,records[i].recorder,records[i].unitPrice);
    }
}

答案 1 :(得分:1)

您正在错误地使用这些数组。试试这个:

i = 0;
while(fscanf(infile1, "%d %s %d %d %f",
            stockCode+i, stockName, stockQuantity+i, stockReorder+i, unitPrice+i) != EOF)
{
    printf("  %3d  %-18s  %3d  %3d  %6.2f \n",
            stockCode[i], stockName, stockQuantity[i], stockReorder[i], unitPrice[i]);
    i++;
}

此外,unitPrice应该是float的数组,而不是int的数组。