[英]reading multiple lines from file into array of structs c
我正在尝试将文件中的数据读取到结构数组中,以供以后用于哈希表。 我终于成功地将数据从第一行存储到一个结构中,但是,当从第二行读取时,信息的输出是不正确的。
这是样本数据的一部分
“ K300”“键盘”“美国通用” 150.00 50
“ R576”“ 16英寸轮辋”“ Toyota 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.