c - 内存问题阻止输入到结构中?

标签 c input struct scanf

我不明白为什么要求用户体重输入的最后一行没有被执行。会不会是内存问题?或者我的结构写错了?或者我是否错误地编写了对 scanf() 的调用?还是以上全部?

#include <stdio.h>

struct date{
  int month;
  int day;
  int year;
};

struct healthProfile{
  char firstName[20];
  char lastName[20];
  struct date birthday;
  float height; //inches
  float weight; //pounds
};



int main(void)
{
  struct healthProfile patient1;

  printf("%s\t", "Please enter the patient's first name:");
  scanf("%s", patient1.firstName);


  printf("%s\t", "Please enter the patient's last name:");
  scanf("%s", patient1.lastName);

  printf("%s\t", "Please enter the date of birth(mm/dd/yyyy)");
  scanf("%2i/%2i/%4i", &patient1.birthday.month, &patient1.birthday.day, &patient1.birthday.year);

  printf("%s\t", "Please enter the patient's height in inches");
  scanf("%.2f", &patient1.height);

  printf("%s\t", "Please enter the patient's weight in pounds");
  scanf("%.2f", &patient1.weight);



  return 0;
}

最佳答案

printf 不同,scanf 的格式说明符不采用精度。编译器应该警告您:

x1.c: In function ‘main’:
x1.c:34:3: warning: unknown conversion type character ‘.’ in format [-Wformat=]
   scanf("%.2f", &patient1.height);
   ^
x1.c:34:3: warning: too many arguments for format [-Wformat-extra-args]
x1.c:37:3: warning: unknown conversion type character ‘.’ in format [-Wformat=]
   scanf("%.2f", &patient1.weight);
   ^
x1.c:37:3: warning: too many arguments for format [-Wformat-extra-args]

去掉精度,你就可以正确阅读了:

printf("%s\t", "Please enter the patient's height in inches");
scanf("%f", &patient1.height);

printf("%s\t", "Please enter the patient's weight in pounds");
scanf("%f", &patient1.weight);

关于c - 内存问题阻止输入到结构中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49139589/

相关文章:

c - massif 的内存计数和 memcheck 的内存计数有什么区别?

c - 在C中按 "Ctrl + c"时退出读监听

c# - 检查文件访问权限,获取进程 ID

c - 当将输入从文件扫描到结构,然后保存更改时,为什么它总是写入第一行并删除其他所有内容?

c - 当我在 C 中 malloc 另一个字符串时,字符串发生变化

从c上的键盘输入字符

c - 错误: too few arguments to function 'strcmp'

algorithm - 在哪里可以找到图形输入资源/文件?

c++ - 如何删除指向(结构/对象)的指针而不破坏(结构/对象)内部的指针?

ios - 基础框架中的结构声明