从文件读取多行到结构数组c

时间:2013-12-02 01:19:16

标签: c arrays struct newline scanf

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

这是样本数据的一部分

“K300”“Keyboard”“US Generic”150.00 50

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

“HL412”“Headlight”“Ford Taurus 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循环之前是否可以正常运行代码

1 个答案:

答案 0 :(得分:0)

你可以这样做。

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);