关闭。这个问题需要debugging details .它目前不接受答案。
想改进这个问题?将问题更新为 on-topic对于堆栈溢出。
5年前关闭。
Improve this question
好的,所以我得到了一个文本文件,其中包含一堆 id、大小和权重。获取此数据的函数位于底部 void listBoxes(const char filename[])。如果用户输入 1,它应该列出文本文件中的所有信息以及我输入的一些标题。当我在我的 main 中调用该函数时,案例 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;
}
最佳答案
与您的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
的值功能。
关于调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40813187/