@Fjottenによって開始された例を続けると、ここではシングル「価格」を読むことができるいくつかの(未テスト、コンパイルされていない)のコードです。それらのすべてをループし、必要なデータ構造(おそらく何らかの種類のオブジェクト配列)に格納する必要があります。
#define ERROR_MSG(...) ... whatever you want ...
#define STREQUAL(a,b) (0 == stricmp(a,b))
typedef struct {
int wood;
int iron;
int bronze;
int diamond;
} PRICE;
PRICE * get_price(FILE * fp) {
char line[80];
int line_no = 0;
char units[80];
int qty;
PRICE * price;
while (fgets(line, sizeof(line), fp)) {
// Skip over blank lines, comments?
if (sscanf(line, " %s %d", units, &qty) != 2) {
ERROR_MSG("sscanf error reading prices, at line %d", line_no);
continue; // break? exit?
}
if ((price = calloc(1, sizeof(PRICE)) == NULL) {
ERROR_MSG("calloc failure reading prices, at line %d", line_no);
exit(1);
}
if (STREQUAL("wood", units)) {
price->wood = qty;
}
else if (STREQUAL("iron", units)) {
price->iron = qty;
}
// else if ...
else {
ERROR_MSG("Unrecognized currency '%s' reading prices, at line %d",
units, line_no);
continue;
}
return price;
}
}
typedef enum {
CHESTPLATE,
HELMET,
NUM_TREASURES
} TREASURE_TYPE;
typedef struct {
TREASURE_TYPE tr_type;
PRICE * tr_base_price;
const char * tr_name;
} TREASURE;
TREASURE Treasures[NUM_TREASURES];
void get_treasures(prices_file) {
if ((fp = fopen(prices_file, "r")) == NULL) {
ERROR_MESSAGE("Unable to open treasure prices file '%s' for reading", prices_file);
exit(1);
}
for (ttype = 0; ttype < NUM_TREASURES; ++ttype) {
Treasures[ttype].tr_type = ttype;
Treasures[ttype].tr_base_price = get_price(fp);
Treasures[ttype].tr_name = "I got nothing!";
}
fclose(fp);
}
ヒント: 'fgets'の' while'と戻り値について知ることができます。あなたはすでにかなり近いです。 – donjuedo
はい、Cは 'for'、' while'、 'do ... while'というループ構造を持っています。 –
各ラインの変数名を構成できないと分かったらすぐにその戦略を再考する必要があります。これは「ループ、ちょうどループ」よりも少しだけ時間がかかります。 – usr2564301