【问题标题】:Fscanf scanning incorrect informationfscanf 扫描不正确的信息
【发布时间】:2015-11-20 14:18:18
【问题描述】:

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

测试文件是.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, " %c", &(user_profile.gender));怎么样
  • 并且,fscanf(file_pointer, "%s", user_profile.first_name); 应该足够了
  • @SouravGhosh,ekstra & 是前一次尝试的迷路,已修复它:-) 至于 %c 前面的空白,没有修复它
  • 关于这一行:void user_profile_loader(struct profile_info user_profile),传递整个数组(几乎)总是一个坏主意。将指针传递给数组要好得多。
  • 在调用fopen()时,始终检查(!=NULL)返回值以确保操作成功。

标签: c scanf stdio


【解决方案1】:
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的返回。

【讨论】:

  • 返回值也应该被检查,但是我们只能重复“如果你读过手册你会注意到这个、这个和这个”在它变得真正好之前。老... :(
  • @Seb 是的,但基本上它不会没用。在某些情况下可能会有所帮助。虽然只是在注释中提到,OP 可能会也可能不会提及它:-)
  • @NikolajLjørring 如果这些功能失败,最好处理
  • @Dream_Reaper 假设您告诉scanf 读取一些整数数据,而用户输入“TROLOLOLOL”... scanf 有什么用?
  • 检查系统函数调用返回值的原因有很多。最明显的是,此类调用可能会失败。这条公理将在编程中为您提供良好的服务:“永远不要相信用户输入有效值。”
猜你喜欢
  • 1970-01-01
  • 2020-10-24
  • 2012-07-14
  • 2016-05-04
  • 1970-01-01
  • 2012-09-15
  • 2022-11-27
  • 2014-03-15
  • 1970-01-01
相关资源
最近更新 更多