簡體   English   中英

從文件讀取到 C 中的數組

[英]Reading from file into an array in C

伙計們。 我在 C 中讀取文件並放入數組時遇到問題,將數組的每個部分分配給一個變量。

該文件如下所示:

A0005:Burger:2.39:Extra Cheese
A0006:Soda:1.35:Coke
....

問題是,當字符串到達​​冒號時,我不太明白如何在 C 中拆分字符串。

到目前為止,我嘗試創建一個結構,嘗試使用 strtok 和 getchar 但到目前為止沒有成功。

這是我到目前為止所得到的

#include <stdio.h>

struct menuItems{
 char itemCode[5];
 char itemName[50];
 float itemPrice;
 char itemDetails[50];
 };


int main(void){
    FILE *menuFile;
    char line[255];
    char c;

    struct menuItems allMenu = {"","",0.0,""};


    if ((menuFile = fopen("addon.txt", "r")) == NULL){
        puts("File could not be opened.");

    }
    else{
        printf("%-6s%-16s%-11s%10s\n", "Code", "Name", "Price", "Details");
        while( fgets(line, sizeof(line), menuFile) != NULL ){
            c = getchar();
            while(c !='\n' && c != EOF){
                fscanf(menuFile, "%5s[^:]%10s[^:]%f[^:]%s[^:]", allMenu.itemCode, allMenu.itemName, &allMenu.itemPrice, allMenu.itemDetails);
            }

            }


    }
}

對於每一行,您需要執行以下操作:

   /* your code till fgets followed by following */
   /* get the first token */
   token = strtok(line, ":");

   /* walk through other tokens */
   while( token != NULL ) {
      printf( " %s\n", token ); /* you would rather store these in array or whatever you want to do with it. */

      token = strtok(NULL, ":");
   }

以下代碼為包含 100 個菜單項的數組分配內存並將給定的文件條目讀入其中。 您實際上可以計算輸入文件中的行數並分配盡可能多的條目(而不是硬編碼的 100):

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

struct menuItem
{
    char itemCode[5];
    char itemName[50];
    float itemPrice;
    char itemDetails[50];
};

int main()
{
    char line[255];
    FILE *menuFile = fopen("addon.txt", "r");
    struct menuItem * items =
        (struct menuItem *) malloc (100 * sizeof (struct menuItem));
    struct menuItem * mem = items;

    while( fgets(line, sizeof(line), menuFile) != NULL )
    {
        char *token = strtok(line, ":");
        assert(token != NULL);
        strcpy(items->itemCode, token);
        token = strtok(NULL, ":");
        assert(token != NULL);
        strcpy(items->itemName, token);
        token = strtok(NULL, ":");
        assert(token != NULL);
        items->itemPrice = atof(token);
        token = strtok(NULL, ":");
        assert(token != NULL);
        strcpy(items->itemDetails, token);
        items++;
   }

   free(mem);
   fclose(menuFile);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM