我需要创建一个程序,它要求用户通过实现结构输入新生婴儿。然而,在打印了“父亲年龄”的信息,要求用户输入年龄后,该程序立即终止。为什么会发生这种情况,如何解决呢?
#include <stdio.h>
#include <stdlib.h>
struct father{
char dad_name[50];
int dad_age;
};
struct mother{
char mom_name[50];
int mom_age;
};
struct baby{
char baby_name[50];
char sex[6];
char birthday[10];
struct father father1;
struct mother mother1;
};
struct baby *b1;
void display(int);
int main(){
int baby_num;
printf("Enter number of baby that is/are going to input: ");
scanf("%d", &baby_num);
display(baby_num);
printf("\nNEW BORN IN KUANTAN HOSPITAL\n");
for(int i=0; i<baby_num; i++){
printf("\nBaby %d\n", i+1);
printf("Baby Name: %s\n", b1[i].baby_name);
printf("Sex: %s\n", b1[i].sex);
printf("Birthday: %s\n", b1[i].birthday);
printf("\nFather name: %s\n", b1[i].father1.dad_name);
printf("Father age: %d", b1[i].father1.dad_age);
printf("\nMother name: %s\n", b1[i].mother1.mom_name);
printf("Mother age: %s\n", b1[i].mother1.mom_age);
};
return 0;
};
void display(int baby_num){
int temp;
b1 = (struct baby*) malloc(baby_num * sizeof(struct baby));
for(int i=0; i<baby_num;i++){
printf("Baby Name: ");
scanf("%d", &temp);
scanf("%[^\n]", b1[i].baby_name);
printf("Sex: ");
scanf("%s", b1[i].sex);
printf("Birthday: ");
scanf(" %s", b1[i].birthday);
printf("Father name: ");
scanf("%d", &temp);
scanf("%[^\n]", b1[i].father1.dad_name);
printf("Father age: ");
scanf("%d", b1[i].father1.dad_age);
printf("Mother name: ");
scanf("%[^\n]", b1[i].mother1.mom_name);
printf("Mother age: ");
scanf(" %d", b1[i].mother1.mom_age);
};
}
发布于 2022-07-27 14:04:32
在显示功能上,对于父亲的年龄和母亲的年龄,你需要发送扫描函数错误的值。
scanf("%d", &(b1[i]).father1.dad_age);
这为我解决了这个问题。
https://stackoverflow.com/questions/73106984
复制相似问题