Input is asked for altogether instead of separately - c

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <memory.h>
#include <ctype.h>
#include <time.h>
struct customer
{
char name[45];
char invoice[4];
char service[2];
char carNo[16];
char fee[3];
bool urgent;
time_t date;
};
/*********************************************************************************************/
void toFile(char*); // will pass string (char*) to it and itll write it to record.txt - DONE
void displayMenu(void); // will display the menu - DONE
void newInvoice(int invoiceNo);
/*********************************************************************************************/
int main()
{
char toContinue;
int invoiceNo =1;
// format of invoices in txt file
do
{
newInvoice(invoiceNo);
invoiceNo += 1;
// asking if user wants to continue to another order or close the program
printf("Do you want to continue? (Y or N) :");
scanf(" %c",&toContinue);
}
while (toContinue !='N' && toContinue !='n');
return 0;
}
/*********************************************************************************************/
void newInvoice(int invoiceNo)
{
// variable declaration
char enter,urgentCH;
int feeINT;
struct customer *newCus;
newCus = (struct customer*) malloc ( sizeof(struct customer));
displayMenu();
enter = fgetc(stdin);
sprintf(newCus->invoice, "%d", invoiceNo);
// customer info being collected
printf("Customer Name:\n");
scanf("%[^\n]%*c", newCus->name);
printf("Vehicle Numb :\n");
scanf("%[^\n]%*c", newCus->carNo);
printf("Service Selection Numb (From Menu):\n");
scanf("%[^\n]%*c", newCus->service);
printf("Urgent? (Y or N ):\n");
scanf(" %c",&urgentCH);
if(urgentCH == 'Y' || urgentCH == 'y')
newCus->urgent = true;
else
newCus->urgent = false;
printf("Fee (from menu):");
scanf("%d",&feeINT);
sprintf(newCus->fee, "%d", feeINT);
time(&newCus->date); // system date and time being taken
// writng to file
toFile("Invoice:\t");
toFile(newCus->invoice);
toFile(" customer: ");
toFile(newCus->name);
toFile(" vehicle: ");
toFile(newCus->carNo);
toFile(" service: ");
toFile(newCus->service);
toFile(" type: ");
if(newCus->urgent)
toFile("urgent");
else
toFile("normal");
toFile(" fee: ");
toFile(newCus->fee);
toFile(" date: ");
toFile(ctime(&newCus->date));
// invoice output
printf("Customer:%s\n vehicle:%s\n Service:%s\n type:%s\n Fee:%s\n Date:%s\n",
newCus->name,newCus->carNo,newCus->service,newCus->urgent?"urgent":"normal",newCus->fee,ctime(&newCus->date));
free(newCus);
}
/*********************************************************************************************/
void displayMenu()
{
printf("Numb Service type Time service fee\n");
printf(" (minutes) Normal Urgent\n");
printf("1 Repair punctured car tyre/piece 10 5 6\n");
printf("2 Car tyre change /piece 15 150 160\n");
printf("3 Mineral Oil Change 20 80 90\n");
printf("4 Synthetic Oil Change 10 130 140\n");
printf("5 Battery Change 5 200 210\n");
printf("6 Head light bulb change /piece 5 6 8\n");
printf("7 Taillight bulb change /piece 5 6 8\n");
printf("8 Car Wash 10 10 12\n");
printf("------------PRESS ANYTHING TO CONTINUE------------\n");
}
/*********************************************************************************************/
void toFile(char* Str2Write)
{
// file opened for writing
FILE *file2write;
file2write = fopen("file.txt","a");
// file opened successfully check
if(file2write == NULL)
exit(1);
// writng
fprintf(file2write,"%s",Str2Write);
// fprintf(fptr,"\n");
// closing
fclose(file2write);
}
/*********************************************************************************************/
The problem is in
void newInvoice(int invoiceNo)
{
// variable declaration
char enter,urgentCH;
int feeINT;
struct customer *newCus;
newCus = (struct customer*) malloc ( sizeof(struct customer));
displayMenu();
enter = fgetc(stdin);
sprintf(newCus->invoice, "%d", invoiceNo);
// customer info being collected
printf("Customer Name:\n");
scanf("%[^\n]%*c", newCus->name);
printf("Vehicle Numb :\n");
scanf("%[^\n]%*c", newCus->carNo);
printf("Service Selection Numb (From Menu):\n");
scanf("%[^\n]%*c", newCus->service);
printf("Urgent? (Y or N ):\n");
scanf(" %c",&urgentCH);
if(urgentCH == 'Y' || urgentCH == 'y')
newCus->urgent = true;
else
newCus->urgent = false;
printf("Fee (from menu):");
scanf("%d",&feeINT);
sprintf(newCus->fee, "%d", feeINT);
time(&newCus->date); // system date and time being taken
This part is giving a weird output:
I'm very new to this. I was told that scanf is a risky command but I don't know how to replace it with something else.

You are right you should probably not use scanf instead use fgets.
Try building off of this code example:
void newInvoice(int invoiceNo)
{
// Input Variable
char userInput[100];
// You make this not a pointer since in
// original code you don't return it anywhere
// and you don't have to deal with managing memory leaks that you were having.
Customer newCustomer;
// COPY PASTE THIS FROM HERE
printf("Customer Name: "); // query for user input
fgets(userInput, sizeof(userInput), stdin); // get the input
userInput[strlen(userInput) - 1] = '\0'; // removes the \n at end when the user press enter
strcpy(newCustomer.name, userInput); // copy userInput into struct
// TO HERE
printf("You Inputted: %s\n", userInput);
// add more options here
}
Example output for running this should be:
Customer Name: David
You Inputted: David
Do you want to continue? (Y or N) :n
Also use the definition of:
typedef struct customer
{
char name[45];
char invoice[4];
char service[2];
char carNo[16];
char fee[3];
bool urgent;
time_t date;
}Customer;
So you don't have to say struct customer every time. Just makes your code look cleaner.

Related

Edit my struct in C with pointer

I want to create an edit function that receives as a parameter by reference the vector of songs. (using pointers)
The user must choose the song number and re-enter the data of that position of the vector.
I created the struct, I am already receiving the values and I am playing. But I do not know how to edit. Anyone to help me start this part?
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <locale.h>
#include <string.h>
struct registry_of_music {
char name[50];
char artist[60];
char url[80];
};
struct registry_of_music music[9];
int main() {
int i;
printf("\nRegistry of Music\n\n\n");
for(i = 0; i <= 3;i++ ){
printf("Name of Music: ");
fflush(stdin);
fgets(music[i].name, 50, stdin);
printf("Name of Artist: ");
fflush(stdin);
fgets(music[i].artist, 60, stdin);
printf("URL of Internet: ");
fflush(stdin);
fgets(music[i].url, 80, stdin);
}
int op;
do
{
printf("1 - Play\n");
printf("2 - Edit\n");
printf("3 - Exit\n");
printf("Please enter a value:");
scanf("%d", &op);
switch(op) {
case 1: play();
break;
case 2: edit();
break;
case 3: printf("Bye\n");
break;
default: printf("Try Again\n");
}
} while (op!=3);
getch();
return(0);
}
void play(){
int i;
for(i = 0; i <= 3;i++ ){
printf("Name ...........: %s", music[i].name);
printf("Artist .....: %s", music[i].artist);
printf("URL .....: %s", music[i].url);
}
}
void edit(){}
The «fill instance of structure» action is absolutely identical if performing on uninitialized structure or initialized. Even if an instance is not initialized, it has some rubbish values in its fields.
On the other hand there is no way to specify default value which will be shown in fgets's prompt and will be available for keyboard edit, unless you're using much more complicated (and NOT included in ISO C standard) tools.

New to C, need assistance with function related to structures

I need to make the second function (search_pb) print all matching names entered in the personal_info struct. Right now if there are two duplicate first names it only prints the first one. For example, if I added
First name: "Albert"
Last name: "Einstein"
Phone number:35245
and also added
First name: "Albert"
Last name: "Wesker"
Phone number:17367
it would only print the first Albert entered instead of both when I search for "Albert". Any ideas on how to change this?
#include <stdio.h>
#include <string.h>
#include "libpb.h"
void add_person(struct phone_book * pb, struct personal_info person)
{
int num = pb->num_people;
strcpy(pb->person[num].first, person.first);
strcpy(pb->person[num].last, person.last);
strcpy(pb->person[num].phone, person.phone);
num++;
pb->num_people = num;
}
void search_pb(struct phone_book pb, char find_name[])
{
int p;
for (p = 0; p < pb.num_people; p++)
{
if (strcmp(find_name, pb.person[p].first) == 0)
{
printf("\nName: %s %s\n", pb.person[p].first,
pb.person[p].last);
printf("Phone: %s\n", pb.person[p].phone);
return;
}
}
printf("No entries with that name. \n");
}
I was given the main function phone_book.c to work with so I just had to make the functions above and a header file:
#include <stdio.h>
#include <string.h>
#include "libpb.h"
int main ()
{
char cont;
char find_name[25];
struct phone_book pb;
pb.num_people = 0;
struct personal_info person;
printf("\n*********************************************\n");
printf("\n Start with entering new contacts! \n");
printf("\n*********************************************\n");
printf("\nWould you like to enter a new contact (Y/N): ");
while(pb.num_people < 20)
{
scanf("%c", &cont);
if (cont == 'Y')
{
printf("Enter a first name: ");
scanf("%s", person.first);
printf("Enter %s's last name: ", person.first);
scanf("%s", person.last);
printf("Enter %s's phone number: ", person.first);
scanf("%s", person.phone);
add_person(&pb, person);
}
else if (cont == 'N') break;
else if (cont == '\n') continue;
else printf("Error: User entered '%c'. Must enter either 'Y' or 'N'\n",
cont);
printf("\nWould you like to enter a new name (Y/N): ");
}
//search phone book by first name and print persons
printf("\n*********************************************\n");
printf("\n Now You can search for names! \n");
printf("\n*********************************************\n");
printf("\nWould you like to search for a name (Y/N)? ");
while(1)
{
scanf("%c", &cont);
if (cont == 'Y')
{
printf("Enter a person's name to search for: ");
scanf("%s", find_name);
//scanf("%c", &tmp);
search_pb(pb, find_name);
}
else if (cont == 'N') break;
else if (cont == '\n') continue;
else printf("Error: User entered '%c'. Must enter either 'Y' or 'N'\n",
cont);
printf("\nWould you like to search for a name (Y/N)? ");
}
return 0;
}
I also already made the necessary header file libpb.h:
#include<stdio.h>
#include<string.h>
#define MAX 20
#define _CRT_SECURE_NO_DEPRECATE
struct personal_info
{
char first[25];
char last[25];
char phone[15];
};
struct phone_book
{
struct personal_info person[MAX];
int num_people;
};
void add_person(struct phone_book *pb, struct personal_info person);
void search_pb(struct phone_book pb, char find_name[]);
A quick-and-dirty circumvention for this would be:
void search_pb(struct phone_book pb, char find_name[])
{
int matches = 0;
int p;
for (p = 0; p < pb.num_people; p++)
{
if (strcmp(find_name, pb.person[p].first) == 0)
{
printf("\nName: %s %s\n", pb.person[p].first,
pb.person[p].last);
printf("Phone: %s\n", pb.person[p].phone);
matches++;
}
}
if(matches == 0)
{
printf("No entries with that name. \n");
}
}
You could however, e.g. change search_pb() type to int, and return the match count after looping through, so that you can print "no matches" in the caller instead of printing them inside the function.

Buffer overflow or something else

I am creating a program, about seat reservations. I was asked to use unsigned short and unsigned int for some of the variables, so that is why they are set like that.
I have a program that works ok. But when I transfer everything inside a function, everything seems to work ok, but inside my structure weird values start to be saved all over the place..
I only want to save the values of the file (from line 2 -> the end of file).
Because I have a structure that to be initialized I have first to read the txt file and numberofseats, I have am declaring this variable (passenger) 2 times..inside the function (local var) and in the main body..
Maybe this causes the problem?
If I don't use a function everything work fine!
So the problematic code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int i,j,numberofseats,temp;
char platenr[8],selection,buff[60];
char firstname[20];
char lastname[20];
char phone[11];
char *p;
typedef struct
{
char fullname[40];
unsigned short phonenr[10];
unsigned int seatnr;
}PASSENGERS;
void readfile( void)
{
FILE *businfo;
businfo = fopen ("bus.txt","r");
if (businfo == NULL)
{
printf("Error Opening File, check if file bus.txt is present");
exit(1);}
else
{
fscanf(businfo,"%s %d",platenr, &numberofseats);
printf("Bus Licence plate Nr is: %s and number of seats is: %d", platenr, numberofseats);
PASSENGERS passenger[numberofseats];
for (j=0;j<numberofseats;j++)
{passenger[j].seatnr=j+1;
strcpy(passenger[j].fullname,"\0");
}
while (fgets(buff,sizeof(buff),businfo)!=0)
{sscanf(buff, "%s %s %d %s", firstname, lastname, &temp,phone);
strcpy(passenger[temp-1].fullname,firstname);
strcat (passenger[temp-1].fullname, " ");
strcat(passenger[temp-1].fullname,lastname);
printf("%s",passenger[temp-1].fullname);
i=0;
for (p=phone;*p!='\0';p++)
{
(passenger[temp-1].phonenr[i])=*p -'0';
i++;
}
}
}
}
int main(void)
{
readfile();
PASSENGERS passenger[numberofseats];
A variable called x in function foo has nothing to do with a variable called y in function bar. In other words: passenger in main and passenger in readfile are different variables. Changing one will not impact the other.
What you want is probably more like this:
int main(void)
{
PASSENGERS passenger[numberofseats];
readfile(passenger);
^^^^^^^^^
Pass array as a pointer
....
}
and
void readfile(PASSENGERS* passenger)
{
....
// REMOVE THIS: PASSENGERS passenger[numberofseats];
}
Beside that notice:
// Global variables gets zero initialized
int i,j,numberofseats,temp;
^^^^^^^^^^^^
Becomes zero at start up
but still you use it in main:
PASSENGERS passenger[numberofseats];
That is probably no what you really want.
Since you try to read the number of seats in the function, it seams you really want to use dynamic memory allocation. Like:
PASSENGERS* readfile()
{
.....
.....
PASSENGERS* p = malloc(numberofseats * sizeof(PASSENGERS));
.....
.....
return p;
}
int main(void)
{
PASSENGERS* passenger = readfile();
.....
.....
free(passenger);
return 0;
}
If you don't want dynamic allocation, you must move the input of numberofseats into main so it is done before declaring the array.
The problem is that you are declaring a local array in the function readfile(), and once this function terminates, it is lost. You need to be able to return the changes to main(). For that you have some options. One is that you may declare the array in main(), and change your function to void readfile(PASSENGERS passenger[]). In this case, you will do something like this:
int main()
{
PASSENGERS passenger[numberofseats];
readfile(passenger);
// more code
You will be basically passing a pointer to the memory location of the elements stored in the array, local to main(), and the function will fill the array, effectively returning the changes.
Another option is to dynamically allocate an array (with malloc() family) in the function, and make it return a pointer like PASSENGERS *readfile(void). This option may be more suitable if the number of seats is not known at compile time, so you need to dynamically grow or shrink the array when necessary. This option however, leaves you the burden of managing the memory manually, like free()'ing the allocated memory when you are done.
Since you say that you will read numberofseats from the file, the latter would be the better idea, so your code will look something like this:
PASSENGERS *readfile(void)
{
FILE *businfo;
PASSENGERS *passenger;
businfo = fopen ("bus.txt","r");
// do the checks, read the numberofseats
passenger = malloc(numberofseats * sizeof *passenger);
// read the values, fill the array
fclose(businfo); // do not forget to close the file
return passenger;
}
int main()
{
PASSENGERS *passenger = readfile();
// more code
free(passenger);
return 0;
}
Ok, so what I did, before starting to work on dynamic allocation is specify the max number of seats in the start of main, and from there I finished my code as follows. I have 2 warning messages though in lines 43, 109 that can't seem to be able to fix.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int i,j,numberofseats,temp;
char platenr[8],selection;
char firstname[20],lastname[20];
char phone[11];
char *p;
typedef struct
{
char fullname[40];
unsigned short phonenr[10];
unsigned int seatnr;
}PASSENGERS;
void readfile(PASSENGERS passenger[])
{ char buff[60];
FILE *businfo;
businfo = fopen ("bus.txt","r");
if (businfo == NULL)
{
printf("Error Opening File, check if file bus.txt is present");
exit(1);}
else
{
fscanf(businfo,"%s %d",platenr, &numberofseats);
printf("Bus Licence plate Nr is: %s, and Number of Seats is: %d.", platenr, numberofseats);
for (j=0;j<numberofseats;j++)
{passenger[j].seatnr=j+1;
strcpy(passenger[j].fullname,"\0");
}
while (fgets(buff,sizeof(buff),businfo)!=0)
{sscanf(buff, "%s %s %d %s", firstname, lastname, &temp,phone);
strcpy(passenger[temp-1].fullname,firstname);
strcat (passenger[temp-1].fullname, " ");
strcat(passenger[temp-1].fullname,lastname);
i=0;
for (p=phone;*p!='\0';p++)
{
(passenger[temp-1].phonenr[i])=*p -'0';
i++;
}
}
}
}
void countfreeseats(PASSENGERS passenger[]){
int freeseats = 0;
for (j=0; j<numberofseats; j++)
{
strcmp(passenger[j].fullname,"\0")==0 ? freeseats = freeseats + 1 : freeseats ;}
printf ("There are %d Free Seats in this Bus. \n", freeseats);
printf("Seats that are Available are:\n");
for (j=0; j<numberofseats; j++)
{if (strcmp(passenger[j].fullname,"\0")==0)
printf ("%u\n", passenger[j].seatnr);
}
freeseats = 0;
}
void changeData(PASSENGERS *target){
unsigned short tempdigit;
printf("Enter Passenger's first name:");
scanf("%s",firstname);
printf("Enter Passenger's last name:");
scanf("%s",lastname);
strcpy(target->fullname,firstname);
strcat (target->fullname, " ");
strcat(target->fullname,lastname);
printf("Enter Passenger's phone Nr:");
scanf("%s",phone);
i=0;
for (p=phone;*p!='\0';p++)
{
(target->phonenr[i])=*p -'0';
i++;
}
}
void searchpassenger(PASSENGERS passenger[], char selection)
{ char tempsel,tmpfirst[20],tmplast[20];
unsigned short tempphone[10];
if (selection == '1')
{ printf("Enter Passenger's first name:");
scanf("%s",tmpfirst);
printf("Enter Passenger's last name:");
scanf("%s",tmplast);
strcat (tmpfirst, " ");
strcat(tmpfirst,tmplast);
for (j=0;j<numberofseats;j++)
if (strcmp(passenger[j].fullname,tmpfirst)==0)
printf ("Passenger %s has Seat Nr #: %u\n",tmpfirst,passenger[j].seatnr);
}
else if (selection == '2')
{ printf("Enter Passenger's Phone Nr:");
scanf("%s",phone);
i=0;
for (p=phone;*p!='\0';p++)
{
(tempphone[i])=*p -'0';
i++;
}
for (j=0;j<numberofseats;j++)
{if (strcmp(tempphone,passenger[j].phonenr)==0)
printf("Passenger %s has Seat Nr %hd already Booked",passenger[j].fullname,passenger[j].seatnr);
}
}
}
void cancelSeat(PASSENGERS *target){
strcpy(target->fullname,"\0");
for (i=0;i<10;i++)
target->phonenr[i]=0;
printf("Seat Nr %d is now Free",temp);
}
void showList(PASSENGERS passenger[])
{
printf("The following Seats are Booked: \n Name, PhoneNr, SeatNr\n\n"); /*Emfanisi minimatos*/
for (i=0; i<numberofseats; i++)
if (strcmp(passenger[i].fullname,"\0")!=0)
{
printf("%s, ",passenger[i].fullname);
for (j=0;j<10;j++)
{printf("%hu",passenger[i].phonenr[j]);}
printf(", %u\n",passenger[i].seatnr);
}
}
void writeFile(PASSENGERS passenger[])
{
FILE * output; /* Dilosi onomatos arxeiou */
output = fopen("output.txt","w"); /*dimiourgia i eggrafi pano se iparxon arxeio me onoma output.txt, mesw tis parametrou w*/
fprintf(output,"%s %d \n",platenr,numberofseats); /* mesw tis fprintf eksagogi pinakidas kai epikefalidas "Diagramma leoforeiou" sto arxeio output.txt. Allagi grammis opou xreiazetai*/
for (i=0; i<numberofseats; i++)
{if (strcmp(passenger[i].fullname,"\0")!=0)
{
fprintf(output,"%s ",passenger[i].fullname);
fprintf(output,"%u ",passenger[i].seatnr);
for (j=0;j<10;j++)
fprintf(output,"%hu",passenger[i].phonenr[j]);
fprintf(output,"%s","\n");
}
}
fclose(output); /* Kleisimo arxeiou*/
printf("File Saved as Output.txt");
}
int main(void)
{
PASSENGERS passenger[53];
readfile(passenger);
do{
printf("\n\nNeo Sistima Katagrafis Thesewn Leoforeiou\n");
printf("Please make a selection:\n\n");
printf("0. Exit\n");
printf("1. Empty Seats \n");
printf("2. Book Specific Seat \n");
printf("3. Advanced Search of Booked Seats\n");
printf("4. Cancel Seat Booking\n");
printf("5. Show List of Booked Seats\n");
scanf(" %c",&selection);
if (selection=='1')
countfreeseats(passenger);
else if (selection=='2')
{
printf("Please give seat nr (between 1 and %d) that you want to book:\n", numberofseats);
scanf("%d",&temp);
if (temp >numberofseats || temp <= 0)
{printf("Error: Seat nr should be between 1 and %d", numberofseats);}
else if (strcmp(passenger[temp-1].fullname,"\0")!=0)
printf("Error: Seat is already booked");
else
changeData(&passenger[temp-1]);
}
else if (selection=='3')
{
char tempsel;
printf("Do you want to search with Name (1) or Phone Nr (2)?\n");
scanf(" %c",&tempsel);
searchpassenger(passenger,tempsel);
}
else if (selection=='4')
{
printf("Please give Seat Nr (between 1 and %d) that you want to Cancel Booking:\n", numberofseats);
scanf("%d",&temp);
if (temp >numberofseats || temp <= 0)
{printf("Error: Seat nr should be between 1 and %d", numberofseats);}
else if (strcmp(passenger[temp-1].fullname,"\0")==0)
printf("Error: Seat is already free");
else
cancelSeat(&passenger[temp-1]);
}
else if (selection=='5') /*Menu 6 - Emfanisi listas kratimenon thesewn taksinomimenon kata ayksonta arithmo*/
{
showList(passenger);
}
} while (selection!='0');
{
writeFile(passenger);
}
}

The function is running wrong on a second time even when its not static

i have made a function of a building that create two buildings now on the second building it hops over some parameters from some reason... why?
now i checked the code a few times and im not using any static varbs so it should not do it... than why it remembers when there is a second run?
UPDATE i did that as said but now its only return false... any help will help
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//defines
#define SIZE 30
#define Q_SIZE 4
#define TRUE 1
#define FALSE 0
struct shape
{
char name[SIZE]; /* name of the shape */
int edgeNum; /* number of edges */
char sPol[Q_SIZE]; /* if the shape is a regular polygrom */
};
int shapeMaker();
int main(void)
{
int check;
check = shapeMaker();
if (check == TRUE)
{
printf("the two shapes are equals!\n");
}
else if (check == FALSE)
{
printf("the two shapes are not equals!\n");
}
system("PAUSE");
return 0;
}
int shapeMaker()
{
struct shape firstShape;
struct shape secondShape;
printf("please enter the first shape name: ");
fgets(secondShape.name, SIZE, stdin);
secondShape.name[strcspn(secondShape.name, "\n")] = 0;
printf("\nnow please enter the number of Edges: ");
scanf("%d", &secondShape.edgeNum);
printf("\nis the shape is regular polygom (yes/no)? ");
scanf("%s", secondShape.sPol);
getchar();
printf("\nplease enter the second shape name: ");
fgets(secondShape.name, SIZE, stdin);
secondShape.name[strcspn(secondShape.name, "\n")] = 0;
printf("\nnow please enter the number of Edges: ");
scanf("%d", &secondShape.edgeNum);
printf("\nis the shape is regular polygom (yes/no)? ");
scanf("%s", secondShape.sPol);
if (firstShape.name == secondShape.name && firstShape.edgeNum == secondShape.edgeNum && firstShape.sPol == secondShape.sPol)
{
return TRUE;
}
else
{
return FALSE;
}
}
Add fflush(stdin); at the beginning of shapeMaker and after fgets

Fread() and fwrite () function

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
void delay (int milliseconds); // for delay function
void menu (); //for choosing a menu
void addacc(); // for adding account
void view (); // for viewing existing list
struct date
{
int date, month, year; //struct for date
};
struct customer
{
char name[40],acctype[10];
int accno, age;
double phone;
float amount;
struct date dob; //calling other struct inside struct
struct date deposit;
struct date withdraw;
} add; //struct variable
void addacc()
{
FILE *fp;
fp=fopen ("cus.txt", "a+");
textcolor (1);
printf ("\n\t\t\t\t");
cprintf ("ADD RECORD");
printf("\n\n\n");
printf ("Enter today's date(date/month/year) \n");
scanf ("%d/%d/%d", &add.deposit.date, &add.deposit.month,&add.deposit.year);
printf ("Enter account number\n");
scanf ("%d", &add.accno);
printf ("Enter customer's name\n");
scanf ("%s", add.name);
printf ("Enter customer's age\n");
scanf ("%d", &add.age); printf ("Enter customer's phone num\n");
scanf ("%f",&add.phone);
printf ("Enter the account type(in words): \n\t 1:Current\n\t 2:Saving\n\t 3:Fixed\n");
scanf ("%s",&add.acctype);
textcolor (2);
cprintf ("Almost done! Just enter the amount you want to deposit: ");
scanf ("%f",&add.amount);
fwrite (&add,sizeof(add),1,fp);
fclose (fp);
}
void view ()
{
FILE *view;
int test=0;
system ("cls");
textcolor (3);
printf ("\n\t\t\t\t");
cprintf ("Customer's List");
printf ("\n\n\n");
textcolor(4);
cprintf ("\tCustomer's Name:");
cprintf ("\tAccount Number:");
cprintf ("\tCustomer's Phone No:");
view=fopen("cus.txt", "r");
while(fread(&add, sizeof(add),1,view)!=0)
{
printf ("%s", add.name);
printf ("%d", add.accno);
printf ("%f", add.phone);
test++;
}
fclose (view);
if (test==0)
{
printf ("NO RECORDS FOUND!");
}
}
void menu ()
{
int n;
printf ("Enter your choice 1, 2\n");
scanf ("%d", &n);
switch (n)
{
case 1:
addacc();
break;
case 2:
view ();
break;
}
}
void main (void)
{
system ("cls");
menu ();
}
Output: when you choose 1 as option
ADD RECORD
Enter today's date
Enter customer's name
etc
output: when you choose option 2 for viewing the list of existing customers
screen blank
So I would like to know is my syntax of fread wrong or of fwrite? why isn't it showing on the screen the entries which I just entered? I am using fread function for reading structures into the file and then I want to print the entries on the screen.
I removed the Windows-specific code and cleaned things up a bit. The code religiously checks whether each scanf() returned the correct value; lazily, it just exits if it doesn't. It also checks that the calls to fopen() work.
Some of the scanf() calls were dodgy. You don't need the & in front of a string name, and you do need %lf to read a double (the phone number — interesting choice of data type). I made sure that newlines appear in the output.
The printing is a bit better, though there are problems of a sort with long names.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void menu(void); // for choosing a menu
void addacc(void); // for adding account
void view(void); // for viewing existing list
struct date
{
int date, month, year; // struct for date
};
struct customer
{
char name[40], acctype[10];
int accno, age;
double phone;
float amount;
struct date dob; // calling other struct inside struct
struct date deposit;
struct date withdraw;
} add; // struct variable
void addacc(void)
{
FILE *fp = fopen("cus.txt", "a+");
if (fp == NULL)
exit(1);
printf("ADD RECORD\n");
printf("Enter today's date(date/month/year) \n");
if (scanf("%d/%d/%d", &add.deposit.date, &add.deposit.month, &add.deposit.year) != 3)
exit(1);
printf("Enter account number\n");
if (scanf("%d", &add.accno) != 1)
exit(1);
printf("Enter customer's name\n");
if (scanf("%s", add.name) != 1)
exit(1);
printf("Enter customer's age\n");
if (scanf("%d", &add.age) != 1)
exit(1);
printf("Enter customer's phone num\n");
if (scanf("%lf", &add.phone) != 1)
exit(1);
printf("Enter the account type(in words): \n\t 1:Current\n\t 2:Saving\n\t 3:Fixed\n");
if (scanf("%s", add.acctype) != 1)
exit(1);
printf("Almost done! Just enter the amount you want to deposit: ");
if (scanf("%f", &add.amount) != 1)
exit(1);
fwrite(&add, sizeof(add), 1, fp);
fclose(fp);
}
void view(void)
{
FILE *view;
int test = 0;
printf("Customer's List\n");
printf("\tCustomer's Name:");
printf("\tAccount Number:");
printf("\tCustomer's Phone No:\n");
view = fopen("cus.txt", "r");
if (view == NULL)
exit(1);
while (fread(&add, sizeof(add), 1, view) != 0)
{
printf("\t%16s", add.name);
printf("\t%15d", add.accno);
printf("\t%20.0f", add.phone);
putchar('\n');
test++;
}
fclose(view);
if (test == 0)
{
printf("NO RECORDS FOUND!");
}
}
void menu(void)
{
int n;
printf("Enter your choice 1, 2\n");
if (scanf("%d", &n) != 1)
exit(1);
switch (n)
{
case 1:
addacc();
break;
case 2:
view();
break;
}
}
int main(void)
{
menu();
return 0;
}
Sample output:
Enter your choice 1, 2
2
Customer's List
Customer's Name: Account Number: Customer's Phone No:
BushraYousuf 12345678 112345987621
PresidentBarackObama 987654321 2021199920
He's got more money stashed away than you have.

Resources