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);
}
Related
I am making a simple database to book restaurant seats using basic file handling. I want to check if the user has entered an already booked seat number. As I am inputting the seat number while in append mode, how do I check if the seat number inputted by the user is already stored in the file or not. Here is a piece of my code -:
struct restaurant
{
int seats, seatNo, seatAmount, pizzaQt, burgerQt, drinkQt, pizzaPrice, burgerPrice, drinkPrice;
char name[20], restaurantName[20];
int foodTotal, total;
int counter;
};
int book()
{
FILE *fp;
struct restaurant r;
char choice, choice1;
r.counter=0;
fp=fopen("Restaurant.txt", "a");
if(fp==NULL)
{
printf("\nFailed to open the file.");
exit(1);
}
else
{
do
{
printf("Proceed to booking...");
getch();
printf("\n\t\t\t\t---BOOK SEAT---");
printf("\n\t\t\tEnter your name : ");
scanf("%s", r.name);
printf("\n\t\t\tEnter the restaurant name (ABC, XYZ, PQR, EFG) : ");
scanf("%s", r.restaurantName);
printf("\n\t\t\tEnter the number of seats : ");
scanf("%d", &r.seats);
**printf("\n\t\t\tEnter the seat number(s) : ");
scanf("%d", &r.seatNo);**
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.
I'm making a c program for a simple library but for some reason the program keeps crashing right on startup. Like there's a menu that is displayed but it doesn't even appear it just crashes. can any one help me?
struct library
{
char name[50];
int id;
int qty;
}books[50],copy[50],delet[50],sort[50];
int i=0;
FILE *mybooks;
int main()
{
int choice; char ans;
int id;
int qty;
int s,o=0,j=0;
char name[50];
mybooks=fopen("D:\\mybooks.txt","r");
if (mybooks == NULL) printf("Error. File not found.");
else
{
while(!feof(mybooks))
{
fscanf(mybooks,"%[^\n] %d %d",books[i].name,&books[i].id,&books[i].qty);
strcpy(copy[i].name,books[i].name);
copy[i].id=books[i].id;
copy[i].qty=books[i].qty;
i++;
}
fclose(mybooks);
}
printf("Welcome to the Library.\n");
do
{
printf("Please choose an option:\n");
printf("1.Insert a book\n");
printf("2.Delete a book\n");
printf("3.Search a book by ID\n");
printf("4.Search a book by name\n");
printf("5.Display all books (sorted by name)\n");
printf("6.Display all books (unsorted)\n");
scanf("%d",&choice);
switch (choice){
case 1:
printf("You will need to enter a name, ID, and quantity of the book.\n");
printf("please enter book name:");
fflush(stdin);
fgets(name,sizeof name,stdin);
printf("please enter book ID:");
scanf("%d",&id);
printf("please enter book quantity:");
scanf("%d",&qty);
InsertBook(name,id,qty);
printf("your book has been added successfully\n");
break;
case 2:
printf("Please enter book ID:");
scanf("%d",&id);
DeleteBook(id);
printf("book successfully deleted.\n");
break;
case 3:
printf("Please enter ID of Book:");
scanf("%d",&id);
s=LinearSearch(id,j);
if (s>=0)
{
printf("Book Found.\n");
printf("Name:%s",books[s].name);
printf("ID:%d\n",books[s].id);
printf("Quantity:%d\n",books[s].qty);
}
else
printf("Sorry, the book doesn't exist.\n");
break;
case 4:
printf("Please enter name of book:");
fflush(stdin);
gets(name);
sorting();
s=BinarySearch(name,0,i);
printf("Book Found.\n");
printf("ID:%d\n",sort[s].id);
printf("Quantity:%d\n",sort[s].qty);
break;
case 5:
sorting();
while (o<i);
{
printf("%s\n",sort[o].name);
o++;
}
printf("\n");
break;
case 6:
while(o<i)
{
printf("%s",books[o].name);
o++;
}
break;
default:
printf("Invalid Choice. Please try again.\n");
break;
}
printf("do you want to choose another option?(y/n) ");
scanf(" %c",&ans);
}while(ans == 'y');
}
(I'm using functions for the library but I don't think they are causing any problem since i didn't call them yet.)
edited the question to add the structure
You have tested an end of file condition before performing any i/o on the input file. And then, when you perform the i/o with fscanf(), you did not test the result to see if the variables were successfully read.
What is happening is that scanf() is probably failing and you do not reach the end of the loop, i.e., the EOF condition. You get stuck in there until one of your assignments (strcpy(copy[i].name,books[i].name);, copy[i].id=books[i].id; or copy[i].qty=books[i].qty;) will finally cause an overflow.
To verify this, run the code in a debugger.
Using fscanf() is very tricky, always test it thoroughly.
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++;
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);