Here is the question:
Suppose we have the user-defined structure baby, including:
· Name is a string
· BirthYear is an integer
· BirthMonth is an integer
· Weight is a real number
· Sex is an integer that receives only 2 values :1 for boys and 0 for girls
a) Read information about babies into array B until we get weight 0 .
b) Read month M (1 ≤ M ≤ 12) and year Y (2000 ≤ Y ≤ 2009)from the keyboard. Display information of babies that were born in month M of year Y with the following format:
Name Weight Sex
Suri Cruise 3.45 F
Romeo Beckham 4.35 M
· Name is displayed in a 40 character space, left justified
· Weight is displayed using ten characters with two digits after the decimal point, right justified.
· Sex is displayed with ‘M’ and ‘F’
Write message “No baby was born in the month M/Y” if no baby matches.
And here is my code:
Code:
#include <stdio.h>
#include <conio.h>
struct baby
{
char Name[50];
int BirthYear;
int BirthMonth;
float Weight;
int Sex; //1 for boys and 0 for girls
};
void main()
{
int i=0, M, Y, num, flag=0;
struct baby B[50];
clrscr();
do
{
i++;
printf("Enter Name: ");
fflush(stdin);
gets(B[i].Name);
printf("Enter BirthYear: ");
fflush(stdin);
scanf("%d", &B[i].BirthYear);
printf("Enter BirthMonth: ");
fflush(stdin);
scanf("%d", &B[i].BirthMonth);
printf("Enter Weight: ");
fflush(stdin);
scanf("%f", &B[i].Weight);
printf("Enter Sex(1 for boys and 0 for girls): ");
fflush(stdin);
scanf("%d", &B[i].Sex);
}
while(B[i].Weight != 0);
num = i;
do
{
printf("Enter month M (1<=M<=12) and year Y (2000<=Y<=2009) separated by space: ");
scanf("%d %d", &M, &Y);
}
while(M>12 || M<1 || Y>2009 || Y<2000);
printf("%-40s%10s\t%s\n", "Name", "Weight", "Sex");
for(i=1; i<num; i++)
{
if(B[i].BirthMonth==M && B[i].BirthYear==Y)
{
printf("%-40s%10.2f", B[i].Name, B[i].Weight);
if(B[i].Sex==1)
printf("\tM\n");
else
printf("\tF\n");
flag = 1;
}
}
if(flag==0)
printf("No baby was born in the month %d/%d", M, Y);
getch();
}
I compiled and ran it using TurboC++. But when i entered just some numbers, the MS-DOS window suddenly closed.
Can you guys tell me where the problem is?
Thank you!