我应该得到一个文件并扫描信息。当我尝试将其打印出来时,我扫描的大部分信息都会丢失或被切掉。这是我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct profile {
char gender;
float soc;
char name[20];
char name2[20];
int age;
char job[20];
float income;
char M_hob[20];
char m_hob[20];
int height;
int weight;
char relig[20];
} PROFILE;
int main(void)
{
int i, count;
char file[30], ssn[10];
FILE *fin;
PROFILE members[50];
printf("SSN: ");
scanf("%s", ssn);
printf("Name of file of records: ");
scanf("%s", file);
fin = fopen(file, "r");
if ((fin == NULL)) {
printf("Can't Open File");
exit(1);
}
i = 0;
while (fscanf(fin, "%c", &members[i].gender) != EOF) {
fscanf(fin, "%f", &members[i].soc);
fscanf(fin, "%s", members[i].name);
fscanf(fin, "%s", members[i].name2);
strcat(members[i].name, members[i].name2);
fscanf(fin, "%d", &members[i].age);
fscanf(fin, "%s", members[i].job);
fscanf(fin, "%f", &members[i].income);
fscanf(fin, "%s", members[i].M_hob);
fscanf(fin, "%s", members[i].m_hob);
fscanf(fin, "%d", &members[i].height);
fscanf(fin, "%d", &members[i].weight);
fscanf(fin, "%s", members[i].relig);
fscanf(fin, "%c", &members[i].space);
i++;
}
fclose(fin);
count = i;
for (i = 0; i <= count; i++) {
printf("%c\n", members[i].gender);
printf("%.0f\n", members[i].soc);
printf("%s\n", members[i].name);
printf("%d\n", members[i].age);
printf("%s\n", members[i].job);
printf("%.0f\n", members[i].income);
printf("%s\n", members[i].M_hob);
printf("%s\n", members[i].m_hob);
printf("%d\n", members[i].height);
printf("%d\n", members[i].weight);
printf("%s\n", members[i].relig);
}
return 0;
}
我正在扫描的两段:
M
111223333
Rob Low
47
Actor
1000000
Dancing
Painting
63
165
Atheist
M
123456789
Bob Mitchell
77
Driver
25000
Baseball
Cooking
72
275
None
和打印出来的部分内容:
M
111223336
Rob
47
Actor
1000000
Dancing
Painting
63
165
Atheist
0
M
0
Bob
0
Mitchell
77
0
0
Driver
2
5000
Baseball
72
275
0
ne
正如你所看到的那样,第一个被完美扫描,但其余的都是错误的。
答案 0 :(得分:1)
如果您必须使用fscanf()
,请检查每个返回值。
担心循环前面的%c
在第二个循环中获取换行符。
你最好将每一行读成一个大字符串,然后将sscanf()
应用于它。这至少避免了对换行的混淆。 (我不会用bargepole触摸scanf()
或fscanf()
因为他们处理换行符的方式 - 或者不是。)