fscanf 扫描不正确的信息

Fscanf scanning incorrect information

我是一名学生,尝试打印 6 行我已插入到名为 test.txt

的 txt 文档中

测试文件是 .txt 中的简单纯文本,以下文本各占一行:

Nikolaj
Ljorring
m
20
182
200

但是,我需要将加载的数据放入如下所示的结构中:

struct profile_info
{
char first_name[30];
char last_name[30];
char gender;
int age;
int height;
double weight;
};

还有一个加载器/打印函数,如下所示:

void user_profile_loader(struct profile_info user_profile)
{
FILE *file_pointer;
file_pointer = fopen("test.txt", "r");

fscanf(file_pointer, "%s", &user_profile.first_name);

fscanf(file_pointer, "%s", user_profile.last_name);

fscanf(file_pointer, "%c", &(user_profile.gender));

fscanf(file_pointer, "%d", &(user_profile.age));

fscanf(file_pointer, "%d", &(user_profile.height));

fscanf(file_pointer, "%d", &(user_profile.weight));

printf("%s \n%s \n€c \n%d \n%d \n%lf", &user_profile.first_name, &user_profile.last_name,
user_profile.gender, user_profile.age, user_profile.height, user_profile.weight);

fclose(file_pointer);
}

然而,我的输出看起来是这样的:

Nikolaj
Ljorring
(wierd C with a line beneath it)c [So a wierd C followed by a normal lowercase c]
10
5
0.000000
fscanf(file_pointer, "%s", &user_profile.first_name);
                           ^ no need of & here 

这里 -

fscanf(file_pointer, "%d", &(user_profile.weight));

您使用 %d 读取 double 值。您传递了错误的参数,它调用了 UB。在这里使用 %lf

在你的printf-

printf("%s \n%s \n€c \n%d \n%d \n%lf", &user_profile.first_name, 
 &user_profile.last_name,user_profile.gender, user_profile.age, user_profile.height, user_profile.weight);

什么是\n€c?您应该使用说明符 %c

注意- 您应该检查 fopenfscanf 的 return。