【问题标题】:read a text file into a struct将文本文件读入结构
【发布时间】:2020-11-20 04:23:40
【问题描述】:

这是将文件读入结构的正确方法吗? 我试过做测试打印,但没有打印出来? 当我运行和编译程序时,没有错误或设置错误。

`int main(){
FILE* f;
linkedList* list = NULL;
house* house;

f = fopen("house.txt", "r");

list = createLinkedList();
if (f == NULL)
{
    printf("Error: File could not be opened.\n");
}  
while (!EOF)
{
    fscanf(f, "%d", &house->price);
    fscanf(f, "%d", &house->bed);
    fscanf(f, "%d", &house->bath);

    insertStart(list, character);
    printf("%d test data %d %d", house->bed, house->price, house->bath);
}
fclose(f);
freeLinkedList(list);
return 0;`

【问题讨论】:

  • while (!EOF)??建议您进行基本调试。在调试器中运行你的程序,它会清楚地显示你的循环没有进入。在 Stack Overflow 上发帖之前,您应该这样做。
  • house 是一个未初始化的指针,因此使用它是未定义的行为。你的文件格式是什么?像while (fscanf(f, "%d%d%d", &house->price, &house->bed, &house->bath) == 3) { ... } 这样的东西可能会更好。

标签: c struct printing readfile


【解决方案1】:

您声明了house* house,但没有创建实际对象。您的指针悬空,因此很可能您的程序正在写入和打印未定义的内存。

【讨论】:

  • 你能解释一下如何在c中创建一个对象
  • a) house h; - 在堆栈上创建对象,然后通过. 访问其成员,例如house.price。 b) house *h = (house*)malloc(sizeof(house)); - 在堆上创建。变体 ab 取决于您的需要,这超出了本主题的范围。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-13
  • 2016-10-24
  • 1970-01-01
相关资源
最近更新 更多