This question is an exact duplicate of:
这个问题与以下内容完全相同:
- reading input from text file into array of structures in c 1 answer
- 在c 1答案中将输入从文本文件读入结构数组
I'm making a program in C with structures. It must read some text from a text file and save it into a struct. When I print the struct, I see my information with some random numbers and characters after it. Can someone help me?
我正在使用结构在C中创建一个程序。它必须从文本文件中读取一些文本并将其保存到结构中。当我打印结构时,我看到我的信息后面有一些随机数字和字符。有人能帮我吗?
#include<stdio.h>
typedef struct {
char naam[32];
int telefoon;
} Persoon;
void drukadres(Persoon*);
int main(void)
{
Persoon p;
FILE *Bestand;
Bestand = fopen("Bestand.txt", "r");
while (fread(&p,sizeof(Persoon),1,Bestand)!=NULL)
{
drukadres(&p);
}
}
void drukadres(Persoon *p)
{
printf("%s %d", p->naam,p->telefoon);
}
This is in my text file:
这是在我的文本文件中:
Vincent 0473352787
Janssens 56445343445
Thanks!
谢谢!
1 个解决方案
#1
2
As your input file is text you must use text input function instead of the binary fread
!
由于您的输入文件是文本,您必须使用文本输入函数而不是二进制fread!
You could use something like :
你可以使用类似的东西:
int main(void)
{
Persoon p;
FILE *Bestand;
char line[64];
int num = 0;
Bestand = fopen("Bestand.txt", "r");
while (fgets(line, sizeof(line), Bestand)!=NULL)
{
num += 1;
if (2 != sscanf("%31s %d", p.naam, &(p.telefoon))) {
fprintf(stderr, "Error line %d\n", num);
break;
}
drukadres(&p);
}
}
#1
2
As your input file is text you must use text input function instead of the binary fread
!
由于您的输入文件是文本,您必须使用文本输入函数而不是二进制fread!
You could use something like :
你可以使用类似的东西:
int main(void)
{
Persoon p;
FILE *Bestand;
char line[64];
int num = 0;
Bestand = fopen("Bestand.txt", "r");
while (fgets(line, sizeof(line), Bestand)!=NULL)
{
num += 1;
if (2 != sscanf("%31s %d", p.naam, &(p.telefoon))) {
fprintf(stderr, "Error line %d\n", num);
break;
}
drukadres(&p);
}
}