我不明白为什么要求用户体重输入的最后一行没有被执行。会不会是内存问题?或者我的结构写错了?或者我是否错误地编写了对 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/