Below is a quick program I created, The program is suppose to keep a trace of blood donors.
#include <stdio.h>
#include <conio.h>
struct donors
{
char name[20];
char address[40];
int age;
int blood_type;
};
void main()
{
int ask,i=0;
struct donors d;
FILE *fp;
fp = fopen("Blood_Donors.txt","r");
clrscr();
if(fp==NULL)
{
printf("Error: Unable to open file.");
printf("\nDo you want to create a new file ? (Y = 1 / N = 0) : ");
scanf("%d",&ask);
if(ask==1)
{
fp = fopen("Blood_Donors.txt","w");
}
if(fp!=NULL)
{
printf("\nFile Created\n");
}
else
{
if(ask==1)
{
printf("\nError: Unable to create file");
printf("\nPress any key to exit the program");
getch();
exit(1);
}
else
{
printf("\nFile not created \nPress any key to exit the program");
getch();
exit(1);
}
}
}
else
{
fp = fopen("Blood_Donors.txt","a");
printf("Do you want to enter a record ? (Y = 1 / N = 0) : ");
scanf("%d",&ask);
}
while(ask==1)
{
i=i+1;
fflush(stdin);
printf("Enter name (Maximum 20 characters) : ");
gets(d.name);
fflush(stdin);
printf("Enter address (Maximum 40 characters) : ");
gets(d.address);
fflush(stdin);
printf("Enter age (Maximum 2 characters) : ");
scanf("%d",&d.age);
fflush(stdin);
printf("Enter Blood Type \n(A- = 1, A+ = 2, B- = 3, B+ = 4, AB- = 5, AB+ = 6, O- = 7, O+ = 8) : ");
scanf("%d",&d.blood_type);
fprintf(fp,"<donor %d>\nName: %s\nAddress: %s\nAge: %d\nType: %d\n\n",i, d.name, d.address, d.age, d.blood_type);
fflush(stdin);
printf("\n\nDo you want to enter another record ? (Y = 1 / N = 0) : ");
scanf("%d",&ask);
}
fclose(fp);
getch();
}
a) how to increase the value of i appropriately ? where i holds the number of the previous donor. b) how to print the details of all donors below age 30 and whose name starts with 's' ?
a)Since you are saving to a file, why not declare the first line of the file as a single number i representing the number of donors so far, followed by i lines of donors?
b)you might want to lookup xml's
您可以将这些用户存储在数据结构中,例如LinkedList,然后遍历链接列表以查找名称以“s”开头的所有用户,您也可以对这些项目进行计数。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.