好的,所以我得到了一个文本文件,里面有一堆id,size和weights.the抓住这些数据的函数位于底部的void listBoxes(const char filename [])。如果用户输入1,它应该列出文本文件中的所有信息以及我输入的一些标题。当我在我的主要情况1中调用该函数时,它只打印标题,并且在尝试打印实际数据时发生错误。我知道我只是部分正确地调用了函数,但我不确定如何从函数中获取数据。
// 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;
}
答案 0 :(得分:1)
与listBoxes()
功能相关的问题是由于使用fscanf()
功能不正确造成的。正确使用手册页中给出的fscanf()
:
int fscanf(FILE *stream, const char *format, ...);
您尚未指定要从中读取输入的文件指针。此外,您还提供了仅由格式化打印功能使用的格式信息,并引用了不存在的b.size[]
的额外索引。正确的用法是:
fscanf(fp, "%d %lf %lf %lf %lf\n", &b.id, &b.size[0], &b.size[1], &b.size[2], &b.weight);
您还没有真正打印读入的信息,因此您应该以您希望的格式进行此操作。
最后,您无需return
来自void
函数的值。