gpt4 book ai didi

c - 从给出地址而不是值的文件中读取

转载 作者:行者123 更新时间:2023-11-30 17:03:31 24 4
gpt4 key购买 nike

所以我正在从用逗号分隔的文件中读取数据。由于某种原因,代码没有遍历整个文件,而只是打印出一种特定的组件类型。

此外,对于 numOfItems 和价格,我只是打印出地址而不是值!

这是我的代码:

typedef struct inventory {
char *componentType;
char *stockCode;
int numOfItems;
int price;
} inventory;


int main(int argc, char** argv)
{

char str[255];
FILE *invf= fopen("inventory.txt", "r");
// creating an array of structs
struct inventory inv[384];
// counter for array position
int counter = 0;
while (fgets(str, 256, invf) != NULL){
char *componentType = strtok(str, " ,");
// the NULL means it will pick up where it left off
char *stockCode = strtok(NULL, " ,");
int *numOfItems = strtok(NULL, " ,");
int *price = strtok(NULL, " ,");

// adding to the struct
inv[counter].componentType = componentType;
inv[counter].stockCode = stockCode;
inv[counter].numOfItems = &numOfItems;
inv[counter].price = &price;
counter++;
}
int i = 0;
for(i =0; i <300; i++){
printf("%s %s %d %d \n", inv[i].componentType, inv[i].stockCode, inv[i].numOfItems, inv[i].price);
}

return EXIT_SUCCESS;
}

CSV 示例

  lightbulb, RES_16M, 711, 1, 16M
lightbulb, RES_16Ms, 7112, 1, 16Mk
card, CAP_2700pf, 75, 26, 2700pf
card, CAP_2700pfs, 75, 262, 2700pff
Current, ASDba, 0, 800, "doesn't follow trend"
Current, TL741, 20, 12, "doesn't either"

最佳答案

您的componenType是一个指向字符的指针。每次读取一行时,都会将指针分配给该行 componentType 。最后,所有库存项目都指向同一位置,即最后读取的值。您必须使用 malloc 为其分配存储空间,然后复制该值。

以同样的方式,您可以将整数元素设置为指向(字符串)变量的指针。但您必须获得。使用atoi() .

进一步注意char str[255];可以包含255个字符,但你问fgets最多读取 256 个字符。您忘记分配终止空字符。

别忘了检查 counter < 384 .

<小时/> 编辑(添加指导)

您正在构建一个包含库存项目的数组。目前您可以读取不超过 384 个项目,即数组的大小。如果项目的数量可以是“任意数量”,那么您需要更动态的数据结构。目前,数组就足够了,但您必须检查读取 list 文件时是否超出界限。

每次阅读一行时,都会将该行从左到右分解为信息项。对于字符串类型的项目,您必须分配内存来保存字符串数据:

   inv[counter].componentType = malloc(strlen(componentType)+1);
strcpy(inv[counter].componentType, componentType);

读取数字信息时,它仍然是字符串,您必须将其转换为整数:

   int numOfItems = atoi(strtok(NULL, " ,"));

或者:

  inv[counter].numOfItems = atoi(strtok(NULL, " ,"));

以这种方式构建数组后,您可以在程序中使用它。要更改组件类型,例如:

   free(inv[counter].componentType );                               // release old memory
inv[counter].componentType = malloc(strlen(newComponentType)+1); // get new
strcpy(inv[counter].componentType, newComponentType);

完成后,您应该释放用 malloc 分配的所有内存。通过调用 free对于每个项目。

关于c - 从给出地址而不是值的文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36133320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com