だから、id、sizes、およびweightsの束を持つテキストファイルを得ました。このデータを取得する関数は、ボトムのvoid listBoxes(const char filename [])にあります。ユーザーが1を入力すると、テキストファイルのすべての情報と、入力したいくつかのタイトルが一覧表示されます。私がメインのケース1で関数を呼び出すと、タイトルだけが印刷され、実際のデータを印刷しようとするとエラーが発生します。私は部分的にのみ関数を正しく呼び出すことがわかっていますが、関数からデータを取得する方法がわかりません。あなたのlistBoxes()
機能に関連関数を呼び出す
// Workshop 9 - Files
// Name:
// Student #:
#include <stdio.h>
struct Box
{
int id; // the box ID
double size[3]; // dimensions of the box (Length, Width, Height)
double weight; // weight of the box
};
void printBox(struct Box b)
{
printf("\nID: %6d\n"
"Length: %6.2lf\n"
"Width: %6.2lf\n"
"Height: %6.2lf\n"
"Weight: %6.2lf\n\n", b.id, b.size[0], b.size[1], b.size[2], b.weight);
}
int menu(void)
{
int choice = -1;
printf("1- List all boxes\n");
printf("2- Find a box\n");
printf("3- Add a box\n");
printf("4- Randomly pick a lucky box!\n");
printf("0- Exit program\n");
printf("Select an option: ");
do
{
scanf("%d", &choice);
if (choice < 0 || choice > 4)
printf("Please enter a number between 0 and 4: ");
} while (choice < 0 || choice > 4);
return choice;
}
int main(void)
{
struct Box b;
FILE * fp = NULL;
int choice; // , boxID, r;
char filename[] = "storage.txt";
printf("Welcome to My Storage Room\n");
printf("==========================\n");
do {
// get user's choice
choice = menu();
switch (choice) {
case 1:
// IN_LAB: list items
listBoxes(filename);
break;
case 2:
// IN_LAB: find a box given its ID
// ask for ID
// call displayBox
break;
case 3:
// AT_HOME: add a box
// get user input for box's ID, size and weight
// call addBox, print message to show number of boxes added
break;
case 4:
// AT_HOME: randomly pick a lucky box
// choose a random number between 1 and the number of boxes in storage
// display the lucky box!
break;
};
} while (choice > 0);
return 0;
}
void listBoxes(const char filename[])
{
struct Box b;
FILE * fp = NULL;
fp = fopen("storage.txt", "r");
if (fp != NULL)
{
printf("List of boxes\n");
printf("=============\n");
printf("ID Length Width Height Weight\n");
printf("-----------------------------\n");
fscanf("%2d %6.2lf %5.2lf %6.2lf %6.2lf\n", &b.id, &b.size[0], &b.size[1], &b.size[2], &b.size[3], &b.weight);
fclose(fp);
}
else
{
printf("Error opening file\n");
}
return 0;
}
ありがとうございます。私の教科書によると、fscanfはファイルから読み込むので、読み方は印刷と同じ責任を取ると誤って判断しました。 –