gpt4 book ai didi

c - 将文件中的多行读入结构体数组 c

转载 作者:行者123 更新时间:2023-11-30 17:43:04 25 4
gpt4 key购买 nike

我正在尝试将数据从文件读取到结构数组中,以便稍后用于哈希表。我终于成功地将第一行的数据存储到结构体中,但是,当从第二行读取时,信息的输出不正确。

这是示例数据的一部分

“K300”“键盘”“美国通用”150.00 50

“R576”“16英寸轮圈”“丰田Verossa”800.00 48

“HL412”“车头灯”“福特金牛座 2010”600.00 52

这是代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define n 99

typedef struct partInfo {
char number[6];
char name[20];
char description[30];
double price;
int qty;
}Part;

Part part[n];

int main() {

char num[6], name[20], desc[30], space[10];
int q, i = 0;
double p;
char ch;

FILE * in = fopen("input.txt", "r");

fscanf(in,"\"%[^\"]", &num);
fscanf(in,"\"%[^\"]", &space);

fscanf(in, "\"%[^\"]", &name);
fscanf(in,"\"%[^\"]", &space);

fscanf(in, " \"%[^\"]s\"", desc);
fscanf(in, "%[^ ]s", &space);

fscanf(in,"%lf", &p);
fscanf(in, "%[^ ]s", &space);

fscanf(in, " %d", &q);
fscanf(in, "%[^\n]s", &space);

strcpy(part[i].number, num);
strcpy(part[i].name, name);
strcpy(part[i].description, desc);
part[i].price = p;
part[i].qty = q;


printf("%s\n", part[i].number);
printf("%s\n", part[i].name);
printf("%s\n", part[i].description);
printf("%.2f\n", part[i].price);
printf("%d\n\n", part[i].qty);
fscanf(in,"%[^\n]", &space); // right here seems to be the problem getting to next line

fscanf(in, "\"%[^\"]", &name);
fscanf(in,"\"%[^\"]", &space);

fscanf(in, " \"%[^\"]s\"", desc);
fscanf(in, "%[^ ]s", &space);

fscanf(in,"%lf", &p);
fscanf(in, "%[^ ]s", &space);
fscanf(in, " %d", &q);

i++;
strcpy(part[i].number, num);
strcpy(part[i].name, name);
strcpy(part[i].description, desc);
part[i].price = p;
part[i].qty = q;

printf("%s\n", part[i].number);
printf("%s\n", part[i].name);
printf("%s\n", part[i].description);
printf("%.2f\n", part[i].price);
printf("%d\n\n", part[i].qty);
fscanf(in,"\"%[^\"]", &space);

fclose(in);
return 0;
}

我还不想使用 while 循环,我想看看在实现 while 循环之前我是否能让代码正常工作

最佳答案

你可以这样做。

fscanf(in, " \"%[^\"]", num);
fscanf(in, "\"%[^\"]s", space);

fscanf(in, " \"%[^\"]", name);
fscanf(in, "\"%[^\"]",space);

fscanf(in, " \"%[^\"]", desc);
fscanf(in, "%[^ ]s", space);

fscanf(in, "%lf", &p);
fscanf(in, "%[^ ]s",space);

fscanf(in, "%d", &q);
fscanf(in, "%[^\n]s", &space);

关于c - 将文件中的多行读入结构体数组 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20319427/

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