【发布时间】:2018-06-03 16:25:25
【问题描述】:
这是一个非常菜鸟的问题。我很抱歉,但我无法让它工作。
我有一个带有布局的文本文件:
movie a
2000
720p
movie b
2002
1080p
movie c
2004
480p
我的代码如下所示:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SOURCE "test.txt"
#define S 50
typedef struct Movie
{
char title[50];
int year;
char quality[7];
}Movie;
int main (void)
{
FILE *f1;
int i = 0;
char buf[3];
int temp;
Movie *movie = NULL;
movie = (Movie*)malloc(sizeof(Movie));
if ((f1 = fopen(SOURCE, "r")) == NULL)
{
perror ("src error!");
printf ("exiting!");
exit (1);
}
while (1)
{
movie = (Movie*)realloc(movie, ((i+1)*sizeof(Movie)));
if (!movie)
{
perror ("mem error");
exit (1);
}
//fgets(movie[i].title, S, f1);
// fscanf(f1, "%s", buf);
// printf("%s", buf);
fscanf(f1, "%[^\n]", movie[i].title);
fscanf(f1, "%d", &movie[i].year);
fscanf(f1, "%s", movie[i].quality);
i++;
if (feof(f1))
break;
}
fclose(f1);
int j=0;
for (;j<=i;j++)
{
printf ("%d :: %s\n ",j, movie[j].title);
printf ("%d :: %d\n ",j, movie[j].year);
printf ("%d :: %s\n\n ",j, movie[j].quality);
}
return 0;
}
从文件读入结构有问题 执行程序时,它会以某种方式搞砸,它将行存储到错误的变量等。 我试过用 fgets 阅读这些行,但我想不通。 任何帮助表示赞赏。 谢谢
编辑: 这是它产生的输出。 似乎是一个非常简单明了的程序。我究竟做错了什么? 谢谢
0 :: movie a
0 :: 2000
0 :: 720p
1 ::
1 :: 0
1 :: movie
2 :: b
2 :: 2002
2 :: 1080p
3 ::
3 :: 0
3 :: movie
4 :: c
4 :: 2004
4 :: 480p
5 ::
5 :: 0
5 ::
【问题讨论】:
-
"...它不知何故搞砸了。"这太不具体了。尝试缩小范围。添加调试输出。检查中间数据。使用调试器。想出一个minimal reproducible example。
-
你好,我添加了一个输出的sn-p。你介意看看吗?谢谢
-
user3121023 您的解决方案有效。非常感谢你。祝你有美好的一天