Data structure and patients records - c

Computerizing health records could make it easier for the patients to share their health profiles and histories among their various health care professionals. A health clinic needs your help to computerize the patients' health records. The patient's records consist of first name, middle name, last name (including SR. JR., etc), gender, date of birth, height (in inches), weight (in pounds). The clinic requires the following features of the program:
read existing record from a file where each patient record is one line entry separating each data with comma
add additional records to file
a function to calculate and return patients age in 3yrs
a function that calculates body mass index with the given formula BMI=(weight-in-pounds X 703)/(height-in-inches X 2) or BMI = (weight-in-kgs)/(height-in-meters X 2)
search patient's name and display patient's information with age and BMI value including category
update patient's information on date of birth, height and/or weight and save updates to file
display all records in tabular format
So far what I have made is:
#include<stdio.h>
#include<stdlib.h>
main(){
FILE*fin;
char name,fname,mname,lname,ename,gender,ch,getch,patient;
int dob,month,day,year,height,weight;
fin=fopen("oldrec.c","w");{
printf("Error: File does not exists");
return 0;
}
{
printf("Add Record? y/n");
ch=toupper(getch);
if(ch='y')
break;
}while (1);
struct patient{
char name;
char fname[20];
char mname[20];
char lname[20];
char gender;
int dob;
int month;
int day;
int year;
int height;
int weight;
printf("/n Patient's Name");
printf("First Name: ");
scanf("%s", &patient.fname);
printf("Middle Name: ");
scanf("%s", &patient.mname);
printf("Last Name: ");
scanf("%s", &patient.lname);
printf("Gender: ");
scanf("%s", &patient.gender);
printf("Date of Birth");
printf("Month: ");
scanf("&d", &patient.month);
printf("Day: ");
scanf("&d", &patient.day);
printf("Year: ");
scanf("%s", %patient.year);
printf("Height: ");
scanf("%d", & patient.height);
printf("Weight: ");
scanf("%d", &patient.weight);
}
I have made another file already, but when I run the codes, it says "Error: File does not exist". What is wrong, and what are the codes for the other problems? Please help me! This is our final requirement on my data structure subject.

fin=fopen("oldrec.c","w");{ // no if
printf("Error: File does not exists"); // all statements will be executed
return 0; // and function will terminate here
}
Ofcourse it will show that message , no condition . No matter if fopen is successful without if all statements will be executed.
Put it in a if block witn a condition .
Write like this -
fin=fopen("oldrec.c","w");
if(fin==NULL){ // check if fin is NULL
printf("Error: File does not exists");
return 0;
}
Other problems are these statements -
scanf("%s", &patient.fname);
...
scanf("%s", &patient.mname);
...
scanf("%s", &patient.lname);
...
scanf("%s", &patient.gender); // use %c for reading char variable
...
scanf("%s", %patient.year); // use %d to read int
^ whats this
Write these statemetns like this -
scanf("%s", patient.fname);
...
scanf("%s", patient.mname);
...
scanf("%s", patient.lname);
...
scanf("%c", &patient.gender);
...
scanf("%d", &patient.year);

Related

How do I pass a airplane row and seat to a txt file together with its passenger name etc.?

We need to make a program for airplane seat reservation. Like we need a program which can reserve, change, delete, and display seats. But our program needs also to be written in a txt file as the user inputs data (name, age, city, seat-e.g., 1F). And I have made a program myself. It runs but exits halfway. And I am not sure if what I'm doing is right. I kind of get the gist on how I can pass informations using structs. But I don't know how I will the seats also in the txt file.
I have these on my first lines:
#include<stdio.h>
#include<malloc.h>
struct Passenger{
int pnum;
int age;
char city[50];
char name[50];
};
struct Seats{
int row;
char seats[10];
};
struct Airplane{
struct Seats seats[6];
};
void intializeDefault(struct Airplane *airplane){
for(int i=0;i<10;i++){
char ch='A';
airplane->seats[i].row=i+1;
for(int j=0;j<6;j++){
airplane->seats[i].seats[j]=ch;
ch++;
}
}
}
And well we kind of have commands, so I put it like:
int main(){
int ch;
struct Airplane airplane;
intializeDefault(&airplane);
do{
printf("Welcome to our Airlines!\n");
printf("\nOptions:");
printf("\n[1] Book a seat.");
printf("\n[2] Display seats.");
printf("\n[3] Change seat.");
printf("\n[4] Delete reservation.");
printf("\n[5] Display reservation records.");
printf("\n[0] Exit.");
printf("\nWhat can we do for you? (Enter number.): ");
scanf("%d", &ch);
switch(ch){
case 1:book();
break;
case 2:display(&airplane);
break;
case 3:change();
break;
case 4:deleteSeat();
break;
case 5:record();
break;
default:
break;
}
}while (ch!=0);
{
printf("\nThank you for booking !");
};
return 0;
}
What I need help on is how should I do on this part:
void book(){
struct Passenger *p;
FILE *fp;
struct Airplane airplane;
intializeDefault(&airplane);
int totalSeats = 60;
int seatsBooked = 0;
int n, i, j, row;
char seat;
printf("How many passengers/seats you want to reserve?: ");
scanf("%d", &n);
p = (struct Passenger*) malloc(n * sizeof(struct Passenger));
fp=fopen("Passengers.txt", "w");
if(seatsBooked==60){
printf("\nAll seats are booked now.");
}
for(i=0;i<n;i++){
printf("Enter Roll Number: ");
scanf("%d", p[i].pnum);
fflush(stdin);
printf("Enter #%d passenger's name: ", i+1);
scanf("%[^\n]s", p[i].name);
fflush(stdin);
printf("What's the passenger's age?: ");
scanf("%d", p[i].age);
fflush(stdin);
printf("Please enter the city where the passenger resides: ");
scanf("%d",p[i].city);
fflush(stdin);
printf("\nEnter Seat row: (Type 1-10) ");
scanf("%d", &row);
fflush(stdin);
printf("Enter Seat column: (Type A-F) ");
scanf("%c", &seat);
if(airplane.seats[row-1].seats[seat-'A']!='X'){
airplane.seats[row-1].seats[seat-'A']='X';
seatsBooked++;
printf("\nSeat %d%c is booked. \n\n", row, seat);
}
else{
printf("\nSeat %d%c is already booked.\n", row, seat);
}
}
fclose(fp);
}
I just need to know on how I can also pass every passenger's seats within on them, and I think I will figure out the other parts. It's because we need to show the records of passengers and their seat reservations when we command "5", and I need to show "X" on every reserved seats when we command "2". And I am not quite sure how I will do that. Should I change the functions on above? The structs? Or some lines?
I gave a quick look and I think that you should keep track of the booked seat by the single user... In your "Seats" struct, why don't you add an array of "Passenger" pointers in order to link every seat to the respective user?
As soon a user books a seat, you should have the index of the booked seat in a specific row. You take the char array and you put an 'X' in that position. Then you take the Passenger* array and in the same position you assign the address of that client's Passenger object.
The one suggestion I would make is to pass along your airplane structure to your various functions. For example:
switch(ch){
case 1:book(&airplane);
break;
Then, down in your "book" function you would use the airplane structure in your code.
void book(Airplane *airplane){
struct Passenger *p;
FILE *fp;
//struct Airplane airplane; /* Or just remove this line of code */
You might want to repeat the referencing of the airplane structure in your other functions as well.
Hope that helps.
Regards.

fprintf function in code writes garbage data into .csv file

I'm trying to create a C program which collect's an applicant's information. When a user is prompted to enter their written subjects, the program writes rubbish data into the .csv file when they wrote one. And sometimes does the same when the number of subjects written is two.
I've tried to clear the buffer stream, but it's no use. Strangely, using different compliers like DevC++, Embarcadero DevC and VS Code produces different results.
Edit: I've also noticed the chances of the rubbish values being written into the file are lowered when the grades of the subjects is lower than the number of subjects written.
Attached below is the code. And an image of the output.
// C libraries.
#include <stdio.h> // Contains function prototypes for the standard input/output library functions, and information used by them.
#include <conio.h> // Contains function prototypes for the console input/output library functions.
#include <stdlib.h> // Contains function prototypes for conversions of numbers to text and text to numbers, memory allocation, random numbers and other utility functions.
#include <string.h> // Contains function prototypes for string-processing functions.
#include <time.h> // Contains function prototypes and types for manipulating the time and date.
#include <stdbool.h> // Contains macros defining bool, true and false, used for boolean variables.
struct Applicant
{
int applicationID;
int dateOfApplication;
char lastName[21];
char firstName[21];
char middleName[21];
char dateOfBirth[21];
int age;
char gender;
char address[100];
char phoneNumber[21];
char emailAddress[51];
char mobileNumber[21];
int numSubjectsWritten;
char csecSubjects[20][100];
char grades[20];
char programmeSelection[10];
};
struct Applicant getApplicantData()
{
struct Applicant applicant;
int i = 0;
int numSubjects;
// Asking for applicant input for various fields.
printf("| Personal |");
printf("\nEnter Last Name: ");
scanf(" %20s", &applicant.lastName);
fflush(stdin);
printf("\nEnter First Name: ");
scanf(" %20s", &applicant.firstName);
fflush(stdin);
printf("\nEnter Middle Name (If you don't have a middle name, leave this field blank.): ");
gets(applicant.middleName);
fflush(stdin);
/*
printf("\nEnter Date of Birth: ");
scanf(" %s", &applicant.dateOfBirth);
fflush(stdin);
printf("\nEnter Gender. 'M' for male, 'F' for female, (M|F): ");
scanf(" %c", &applicant.gender);
fflush(stdin);
printf("\n\n| Contact Information |");
printf("\nEnter Address: ");
gets(applicant.address);
fflush(stdin);
printf("\nEnter Phone Number: ");
gets(applicant.phoneNumber);
fflush(stdin);
printf("\nEnter Email Address: ");
gets(applicant.emailAddress);
fflush(stdin);
printf("\nEnter Mobile Number: ");
gets(applicant.mobileNumber);
fflush(stdin);
*/
printf("\n\n| Education |");
printf("\nEnter Number of Subjects Written: ");
scanf("%d", &applicant.numSubjectsWritten);
fflush(stdin);
while (i < applicant.numSubjectsWritten)
{
printf("\nEnter the subject: ");
gets(applicant.csecSubjects[i]);
fflush(stdin);
printf("\nEnter the grade for that subject: ");
scanf(" %c", &applicant.grades[i]);
fflush(stdin);
i++;
}
return applicant;
}
int main(void)
{
FILE *file = fopen("Data.csv", "a+");
int i, j;
if (!file)
{
printf("\nError! Can not open data file.\nPlease contact the Program Addmission Manager as soon as possible with the error message.");
exit(1);
}
else
{
struct Applicant applicant = getApplicantData();
//fprintf(file, "%s:%s:%s:%s:%c:%s:%s:%s:%s", applicant.lastName, applicant.firstName, applicant.middleName, applicant.dateOfBirth, applicant.gender, applicant.address, applicant.phoneNumber, applicant.emailAddress, applicant.mobileNumber);
fprintf(file, "%s:%s:%s:", applicant.lastName, applicant.firstName, applicant.middleName);
for (i = 0; applicant.csecSubjects[i][0] != '\0'; i++)
{
fprintf(file, " %s", applicant.csecSubjects[i]);
fflush(stdout);
fflush(stdin);
fflush(file);
fprintf(file, " ( %c):", applicant.grades[i]);
fflush(stdout);
fflush(stdin);
fflush(file);
}
}
return 0;
}
First problems I see:
Remove the & from all instances where you scanf a string
Don't use gets, or mix scanf and fgets
Don't fflush(stdin)
Instead of scanf, consider using a custom-made input method with condition checking and anything you need. I will give an example.
#define BUFFER_SIZE 512
void input(char* buffer){
memset(buffer, 0, BUFFER_SIZE); // Initializing the buffer.
fgets(buffer, BUFFER_SIZE, stdin);
strtok(buffer,"\n");
}
How to take input using that?
void main(){
int username[BUFFER_SIZE];
input(username);
}
A way to write a structure to a file is shown below.
void Structure_Print(Applicant* applicant, FILE* stream, int no_of_applicant){
if(no_of_applicant==0){
fprintf(stdout, "No applicant yet.\n");
return;
}
fprintf(stream, "%s:%s:%s:", applicant.lastName, applicant.firstName, applicant.middleName);
for (i = 0; applicant.csecSubjects[i][0] != '\0'; i++)
{
fprintf(stream, " %s:", applicant.csecSubjects[i]);
fprintf(stream, " %c:", applicant.grades[i]);
}
return;
}
Also, I noticed how you tried to make it readable while saving it in subject(grade) format. I recommend you to not do that. Your .csv file is just for database. Nobody is going to read it. So just store the data by comma or any character separator. It will make it easier to extract data later.

How to add line number to only a specific line in a file

I'm creating the inputs of a disease and information on it. The disease should have a number beside it but the remaining inputs should remain as is. How can i add the information to a file but have the disease number increment as it reads new inputs as the program closes?
I've tried using a variable to print the disease number as it goes, but i dont understand how to increment it.
void CreateNew(){
int diseasenum=1;
FILE*fptr;
fptr = fopen("Lifeline Medical & Diagnostic Center.txt", "a+");
if(fptr == NULL)
{
printf("Error! There is no file to write to. Please Create a file");
exit(1);
}
fflush(stdin);
printf("Enter the name of the disease you would like to give detail of: ");
gets(Dissarray.Disease);
if()
fprintf(fptr,"%d\tDisease: %s\n\n",diseasenum,Dissarray.Disease);
printf("\n");
fflush(stdin);
Dissarray.Lethality=0;
printf("What is the Lethality of %s?\t(Answer in percentage. Sample:90 OR 12, etc)\n",Dissarray.Disease);
if (scanf("%d", &Dissarray.Lethality)!= 1)
{
printf("This is not an appropriate number. Please enter appropriately.\n");
fflush(stdin);
scanf("%d", &Dissarray.Lethality);
}
fprintf(fptr,"Lethality: %d\n",Dissarray.Lethality);
printf("\n");
fflush(stdin);
printf("How is %s acquired. (Sample: Contagious Disease, STI, Hereditary)\n",Dissarray.Disease);
gets(Dissarray.ContagionFactor);
fprintf(fptr,"Contagion factor: %s\n",Dissarray.ContagionFactor);
printf("\n");
printf("How is %s Transmitted?\t\t(Sample: Airborne, Touch, Sex, Sneezing, etc.)\n",Dissarray.Disease);
gets(Dissarray.Spread);
fprintf(fptr,"Spread: %s\n",Dissarray.Spread);
printf("\n");
fflush(stdin);
Dissarray.Fatalities=0;
printf("On a yearly basis. What is the average Fatality count brought by %s?\t\t(How many have died to this disease? Sample:100000)\n",Dissarray.Disease);
if(scanf("%d", &Dissarray.Fatalities)!= 1)
{
printf("This is not an appropriate number. Please enter appropriately.\n");
fflush(stdin);
scanf("%d", &Dissarray.Fatalities);
}
fprintf(fptr,"Fatalities: %d\n",Dissarray.Fatalities);
printf("\n");
fflush(stdin);
printf("Has %s been known to evolve under any conditions?\n",Dissarray.Disease);
printf("What is the Sensitivity?\t\t(Sample:Temperatures over 90 degrees OR None.)\n");
gets(Dissarray.Sensitivity);
fprintf(fptr,"Sensitivity: %s\n\n",Dissarray.Sensitivity);
printf("\n");
printf("This ends the entry of info into the file\n");
fclose(fptr);
}
to answer your question about line numbering:
regarding:
int diseasenum=1;
change to:
static int diseasenum=1;
Then, before exiting the function:
diseasenum++;

writing to a file using for loop in c programming

struct customer information[6];
int count,loop;
printf("How many records do you want to add?\n");
scanf("%d",&loop);
FILE *ptr;
ptr = fopen("information.txt","w+");
if(!ptr)
{
printf("file could not be opened\n");
getchar();
return -1;
}
for(count=1; count<=10; count++)
{
printf("Please enter the customer's id number:\n");
scanf("%d",&information[6].idnum);
printf("Please enter the customer's first name and last name:\n");
scanf("%s%s",information[6].Fname,information[6].Lname);
printf("Please enter the customer's car model type:\n");
scanf("%s",information[6].cartyp);
printf("Please enter the customer's license plate number:\n");
scanf("%s",information[6].Licnum);
printf("Please enter the customer's car difficulty:\n");
scanf("%s",information[6].Crdffcty);
fprintf(ptr,"%d\%s\%s\%s\%s\%s\n",information[6].idnum,information[6].Fname,
information[6].Lname,information[6].cartyp,information[6].Licnum,
information[6].Crdffcty);
if(loop==count)
{
continue;
}
}
fclose(ptr);
}
i am trying to write to a file using for loop but when i run the code the program doesn't loop more than one times. An error message comes up saying the program stopped working and nothing is in the text document created. i tried some of the suggestions on this site but it seems there is something else wrong with the coding. there are no errors or warning messages. Can someone tell me what i did wrong?
You have your struct defined with 6, and you are trying to access index 6, that is the 7th element. So, you have to make this, supposing that you want the last element:
struct customer information[6];
int count,loop;
printf("How many records do you want to add?\n");
scanf("%d",&loop);
FILE *ptr;
ptr = fopen("information.txt","w+");
if(!ptr)
{
printf("file could not be opened\n");
getchar();
return -1;
}
for(count=1; count<=10; count++)
{
printf("Please enter the customer's id number:\n");
scanf("%d",&information[5].idnum);
printf("Please enter the customer's first name and last name:\n");
scanf("%s%s",information[5].Fname,information[5].Lname);
printf("Please enter the customer's car model type:\n");
scanf("%s",information[5].cartyp);
printf("Please enter the customer's license plate number:\n");
scanf("%s",information[5].Licnum);
printf("Please enter the customer's car difficulty:\n");
scanf("%s",information[5].Crdffcty);
fprintf(ptr,"%d\%s\%s\%s\%s\%s\n",information[5].idnum,information[5].Fname,
information[5].Lname,information[6].cartyp,information[5].Licnum,
information[5].Crdffcty);
if(loop==count)
{
continue;
}
}
fclose(ptr);
}

What is wrong with the following code? I am trying to search for a record in a text file

The program runs fine till I create the file and enter records from structure, but when I try to search a record by using roll no, it crashes.
I am using a structure called student to store data and then I am creating a text file and then I use a for loop to write data on the text file. Then I reopen the file and try to search a record using student roll no.
Program runs fine until I try to search the student roll no. It crashes right after I enter the student roll no to be searched.
Can anyone tell me what modification is needed to make the search work?
Below is my code:
#include<stdio.h>
struct student {
int roll_no;
char name [80];
int age;
}st[30],s;
int main ()
{
int i,n;
char fname[80];
int search;
int found;
FILE *fp;
printf("\nEnter the file name : \n");
scanf("%s",fname);
fp=fopen(fname,"w");
if(fp==NULL)
{
printf("\nCannot create file :");
exit(0);
}
printf("\nNumber of students : \n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\nInformation for student#%d : \n\n",i+1);
printf("\nStudent roll number : \n" );
scanf("%d",&st[i].roll_no);
printf("\nStudent name: \n: ");
scanf("%s",st[i].name);
printf("\nStudent age : ");
scanf("%d", &st[i].age);
}
fprintf(fp, "\nStudent roll no\t\t Student name\t\t student age\t\t\n\n");
for(i=0;i<n;i++)
{
fprintf(fp, "\n%d \t\t %s \t\t %d \t\t", st[i].roll_no,st[i].name,st[i].age);
}
fclose(fp);
fp=fopen(fname,"r+t");
if(fp==NULL)
{
printf("\nCannot open file\n");
exit(0);
}
printf("\n\nStudent roll no to be searched : ");
found=0;
scanf("%d", search);
while(!(feof(fp)) && (found==0))
{
fscanf(fp,"%d,%s,%d",&s.roll_no,s.name,&s.age);
if(s.roll_no==search)
{
fseek(fp,-sizeof(struct student), SEEK_CUR);
printf("\nEnter new name : \n");
scanf("%s", s.name);
fprintf(fp, "\n%d \t\t %s \t\t %d \t\t", s.roll_no,s.name,s.age);
found=1;
}
}
if(found=0)
{
printf("\nStudent record doesn't exist \n");
}
fclose(fp);
return 0;
}
In your code, you're missing an address-of operator in scanf(), thereby passing an invalid type of argument. Basically
scanf("%d", search);
should be
scanf("%d", &search);
That said, it is always a good practice to size-limit the inputs for string, like, for an array defined like char fname[80];, you should use
scanf("%79s",fname);
to avoid possible buffer overflow by excessively long input.
Also, always check for the return value of scanf() and family of functions to ensure their success.

Resources