c - 从文件中读入C中的数组

标签 c arrays

伙计们。 我在用 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);
}

关于c - 从文件中读入C中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46902041/

相关文章:

c - 从输入动态分配矩阵 - C

c - 将strtok结果插入char*(增加动态)

C 函数指针转换为 void 指针

c - 如何修复将指针强制转换为整数?

javascript - 函数或循环不工作

c - 从管道读取时返回不正确的数据

c - 如何将数组中的5个数字写入二进制

c - 如何在C中将两个一维数组相乘后生成一个二维数组?

java - 25个类对象的数组

python - 传递给线程时求和 numpy.ndarray 失败