#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.
Related
Before getting to the root of the problem I will show my code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TITLE_BOOK 1000
#define MAX_AUTHOR_BOOK 1000
#define MAX_CATEGORY_BOOK 1000
#define MAX_NAME_BORROW 1000
typedef struct
{
char title[MAX_TITLE_BOOK];
char author[MAX_AUTHOR_BOOK];
char category[MAX_CATEGORY_BOOK];
int code;
}Book ;
typedef struct
{
char name[MAX_NAME_BORROW];
int id;
int codeBorrow;
int dateBorrow[3];
int dateReturn[3];
}Borrow;
void add(Book x[], int y){
int i;
for(i = 0; i < y; i++){
printf("Menu ke-%d", i+1);
printf("\nEnter the Book Title: ");
scanf("%s", x[i].title);
printf("\nEnter Book Author: ");
scanf("%s", x[i].author);
printf("\nEnter the Book Category: ");
scanf("%s", x[i].category);
printf("\nEnter Book Code: ");
scanf("%d", &x[i].code);
}
}
void save(Book x[], int y){
FILE* f_book;
f_book = fopen("book-data.txt", "w");
if(f_book == NULL){
printf("\nUnable to open file, check file location or permissions\n");
return;
}
int i;
for(i = 0; i < y; i++){
fprintf(f_book, "%s %s %s %d\n", x[i].title, x[i].author, x[i].category, x[i].code);
}
printf("\nData successfully saved to database\n");
fclose(f_book);
}
int main(){
char username[10] = "admin", password[10] = "admin";
char checkUser[10],checkPass[10];
int menu, limit = 0, total_books = 0, dataBook;
Book s_book[1000];
do{
printf("\t\n================================");
printf("\n\tLogin Page");
printf("\t\n================================");
printf("\n");
printf("\nMasukan Username: ");
scanf("%s", checkUser);
fflush(stdin);
printf("\nMasukan Password: ");
scanf("%s", checkPass);
fflush(stdin);
if(strcmp(checkUser, username) == 0 && strcmp(checkPass, password) == 0){
printf("\nSuccessfully Login");
break;
}else{
printf("\nUsername or Password Wrong!");
}
limit++;
}while(limit < 3);
if(limit > 3){
printf("\nToo many request, try again in 30 seconds.");
}
if(limit < 3){
do{
printf("\n");
printf("\n\t=================================");
printf("\n\tSystem Library IT Telkom Surabaya");
printf("\n\t=================================");
printf("\n1. Add Data");
printf("\n2. Read Data");
printf("\n3. Change/Update Data");
printf("\n4. Search Data");
printf("\n5. Sort Data");
printf("\n6. Borrow Book");
printf("\n7. Return Book");
printf("\n0. Exit");
printf("\nMenu: ");
scanf("%d", &menu);
fflush(stdin);
switch(menu){
case 1:
printf("\nInput Total Buku: ");
scanf("%d", &dataBook);
fflush(stdin);
add(s_book, dataBook);
save(s_book, dataBook);
break;
default:
printf("\nMenu not available, re-enter");
break;
}
}while(menu != 0);
}
return 0;
}
so my problem is why my divscode terminal doesn't want to issue login program and only blank in terminal. like this enter image description here. Idk why this is happen, this errro happen after i make procedure for case 1, that is add and save.
I want my code to run normally, like can input and show the output
I create a program that prompts the user to choose an option, like below:
create a file and name the file.
add component in the file
display the item in the file
exit program
So my problem is the file is created and exists in my directory, but it is empty, so where did I miss something? plus can you check whether the 2 and 3 option program are OK?
Here my program:
#include <stdio.h>
#include <stdlib.h>
int main() {
int num, name;
start:
printf("\n1. Create a file.");
printf("\n2. Add a component to the list.");
printf("\n3. Display the current list of component.");
printf("\n4. Exit program.");
printf("\n\nChoose either these four menu = ");
scanf("%d", &num);
fflush(stdin);
switch (num) {
case 1:
printf("\n\nPlease enter file name: ");
scanf("%d", &name);
FILE *pf = NULL;
char username[250];
char userfile[255];
printf("username: ");
scanf("%s", username);
sprintf(userfile, "%s.txt", username);
fflush(stdin);
goto start;
break;
case 2:
pf = fopen(userfile, "w");
if (!pf) {
fprintf(stderr, "File opening failed!\n");
return EXIT_FAILURE;
}
struct date {
int day;
int month;
int year;
};
struct details {
char name[20];
int price;
int code;
int qty;
struct date mfg;
};
struct details item[50];
int n, i;
printf("Enter number of items:");
scanf("%d", &n);
fflush(stdin);
for (i = 0; i < n; i++) {
fflush(stdin);
printf("Item name: \n");
scanf("%s", item[i].name);
fflush(stdin);
printf("Item code: \n");
scanf("%d", &item[i].code);
fflush(stdin);
printf("Quantity: \n");
scanf("%d", &item[i].qty);
fflush(stdin);
printf("price: \n");
scanf("%d", &item[i].price);
fflush(stdin);
printf("Manufacturing date(dd-mm-yyyy): \n");
scanf("%d-%d-%d", &item[i].mfg.day,
&item[i].mfg.month, &item[i].mfg.year);
}
fclose(pf);
goto start;
break;
case 3:
pf = fopen(userfile, "r");
if (!userfile) {
fprintf(stderr, "File opening failed!\n");
return EXIT_FAILURE;
}
{
printf(" ***** INVENTORY ***** \n");
printf("------------------------------------------------------------------\n");
printf("S.N.| NAME | CODE | QUANTITY | PRICE | MFG.DATE \n");
printf("-------------------------------------------------------- ---------\n");
for (i = 0; i < n; i++)
fprintf("%d %-15s %-d %-5d %-5d %d/%d/%d \n",
i + 1, item[i].name, item[i].code, item[i].qty,
item[i].price, item[i].mfg.day, item[i].mfg.month,
item[i].mfg.year);
printf("------------------------------------------------------------------\n");
}
fclose(pf);
goto start;
break;
case 4:
printf("Exit Program, Thank You, Sayonara");
break;
}
return 0;
}
There are multiple problems in your code:
the test if (!userfile) is incorrect: you should test if (!pf) instead
you open the file for reading, you should open it for writing with "w", or possibly for appending with "a".
you never write to the file. You should use fprintf(pf, ...) instead of printf.
the arrays userfile, item and variables i and n are local inside the switch statement: their contents go out of scope when you go to the start label outside de switch statement. Move all these definitions outside the switch statement.
fflush(stdin); has undefined behavior. You can consume (flush) the rest of the input line with: int c; while ((c = getchar()) != EOF && c != '\n') continue; You can define a function flush() that does it.
#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.
Im basically Writing a program that creates, reads, updates and
deletes records in a binary file.
Everything compiles correctly, no syntax errors, but I do have some
bugs.
KNOWN BUGS
1.) Imputing any strings does not work, using fgets
2.) Ctrl-D Does Work but outputs a 'default' error before it exits.
3.) Update does not work (Not my main issue at the moment as the others are more important for now.)
4?) I'm not sure if the menu is working how it's supposed to work. I
think the do while is correct, since in the menu if I select and hit
CTRL-D it does exit the program. Just wanna be sure.
Right now I just want to know why, It is skipping the courseName in
the inputs function.
Here is my code thus far
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
typedef struct{
char courseName [64];
char courseSched [4];
unsigned int courseHours;
unsigned int courseSize;} COURSE;
FILE *pfileCourse;
int courseNumber = 0;
//Prototypes
void inputDetails(COURSE *c);
void readCourseRecord();
void createCourseRecord();
void print_menu();
void modifyCourseInfo();
void deleteCourse();
void display(COURSE c);
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
char choice; // this is the choice
printf("Enter one of the following actions or press CTRL-D to exit\n");
printf("C - Create a new course record\n");
printf("R - Read an existing course record\n");
printf("U - Update an existing course record\n");
printf("D - Delete an existing course record\n");
do{
choice = getchar();
switch(choice) {
case 'c':
case 'C':
printf("YOU PICKED C for Create\n");
createCourseRecord();
break;
case 'r':
case 'R':
printf("This is Choice R\n");
readCourseRecord();
break;
case 'u':
case 'U':
printf("Here is where you update an existing course\n");
modifyCourseInfo();
break;
case 'd':
case 'D':
printf("here is where you Delete an existing course record\n");
deleteCourse();
break;
default:
printf("Wrong Choice!\n");
}
}while(choice != EOF);
return 0;
}
void createCourseRecord() {
COURSE data;
pfileCourse = fopen("courses.dat", "ab");
printf("Please Enter The Details of The Course\n");
inputDetails(&data);
fwrite(&data, sizeof(data), 1, pfileCourse);
fclose(pfileCourse);
printf("Course Has Been Created!\n");
}
void inputDetails(COURSE *c) {
printf("Enter a course number: \n");
scanf("%d", &courseNumber);
printf("Enter a Course Name: \n");
fgets(c->courseName, sizeof(courseName), stdin);
printf("Enter the course schedule (MWF or TR): \n");
fgets(c->courseSched, 4, stdin);
fflush(stdin);
printf("Enter the course credit hours: \n");
scanf("%d",&c->courseHours);
fflush(stdin);
printf("Enter Number of Students Enrolled: \n");
scanf("%d",&c->courseSize);
return;
}
void readCourseRecord(){
COURSE data;
int flag = 0;
int readCourseNumber = 0;
printf("Please Enter a Course Number to Display\n");
scanf("%d", &readCourseNumber);
fflush(stdin);
pfileCourse = fopen("courses.dat", "rb");
while((fread(&data, sizeof(data), 1, pfileCourse)) > 0) {
if(readCourseNumber == courseNumber)
{
display(data);
flag = 1;
}
}
fclose(pfileCourse);
if(flag == 0)
printf("Course not Found!\n");
}
void deleteCourse(){
int newCourseNum;
COURSE data;
FILE *file2;
printf("Please Enter The Course You Wish You Delete\n");
scanf("%d", &newCourseNum);
pfileCourse = fopen("courses.dat", "rb");
file2 = fopen("temp.dat", "wb");
rewind(pfileCourse);
while((fread(&data, sizeof(data), 1, pfileCourse)) > 0)
{
if(courseNumber != newCourseNum)
{
fwrite(&data, sizeof(data), 1, file2);
}
}
fclose(file2);
fclose(pfileCourse);
remove("courses.dat");
rename("temp.dat", "courses.dat");
printf("%d was Successfully deleted\n", newCourseNum);
}
void modifyCourseInfo()
{
COURSE data;
int newCourseNum, found = 0;
printf("Modify\n");
printf("Please Enter The Course You Wish You Modify\n");
scanf("%d", &newCourseNum);
pfileCourse = fopen("courses.dat", "rb+");
while ((fread(&data, sizeof(data), 1, pfileCourse)) > 0 && found == 0)
{
if (courseNumber == newCourseNum)
{
display(data);
printf("Please Enter New Details\n");
inputDetails(&data);
fseek(pfileCourse, - (long)sizeof(data), 1);
fwrite(&data, sizeof(data), 1, pfileCourse);
printf("Course Updated\n");
found == 1;
}
}
fclose(pfileCourse);
if(found == 0)
printf("ERROR: course not found\n");
}
void display(COURSE c){
printf("courseNumber:\t %d\n", courseNumber);
printf("courseName:\t %s\n",c.courseName);
printf("courseSched:\t %s\n",c.courseSched);
printf("courseName:\t %d\n",c.courseHours);
printf("courseSize:\t %d\n",c.courseSize);
}
It doesn't skip courseName, courseName just gets value '\n' because scanf function stops reading your input BEFORE white space. Scanf ignores any whitespace characters encountered before the next non-whitespace character. So you can just add
scanf("%d[^\n]", &courseNumber);
getchar();
after every scanf you have but I'd recommend you to use fgets function for every interactive input.
#include <stdio.h>
#include <string.h>
typedef struct//Declares structure to hold seven created datatypes.
{
int client_id;
char client_business_name [30];
char client_first_name [20];
char client_last_name [20];
char client_address [40];
float client_budget;
char client_business_info [300];
}Client;
main()
{
Client c[100];
void main_menu (Client[]);
main_menu (c);
system ("PAUSE");
}
void main_menu (Client c[])//Determines what the user wants to do and grants access to one of the 6 functions.
{
int choice;
do{
printf ("1.Add Client\n2.Delete Client\n3.Search Clients\n4.Change Client Information\n5.View Clients\n6.Terminate Program\nChoose an option from above:");
scanf ("%d",&choice);
}while (choice<1||choice>6);
if (choice==1)
{
system ("cls");
void accept (Client []);
accept (c);
}
if (choice==2)
{
system ("cls");
void realocate (Client []);
realocate (c);
}
if (choice==3)
{
system ("cls");
void search (Client []);
search (c);
}
if (choice==4)
{
system ("cls");
void change (Client []);
change (c);
}
if (choice==5)
{
system ("cls");
void view_sort (Client []);
view_sort (c);
}
if (choice==6)
{
system ("cls");
void end (Client []);
end (c);
}
}
void accept (Client c[])//Accepts data from the user.
{
int num,y=0;
printf("How Many Clients Do You Want To Add:");
scanf ("%d",&num);
system ("cls");
while (y<num)
{
printf ("\nEnter Client ID:");
scanf ("%d",&c[y].client_id);
printf ("Enter Buisness Name:");
scanf (" %[^\n]",c[y].client_business_name);
printf ("Enter Client First Name:");
scanf (" %[^\n]",c[y].client_first_name);
printf ("Enter Client Last Name:");
scanf (" %[^\n]",c[y].client_last_name);
printf ("Enter Buisness Address:");
scanf (" %[^\n]",c[y].client_address);
printf ("Enter Client Budget:");
scanf ("%f",&c[y].client_budget);
printf ("Enter Buisness Information:");
scanf (" %[^\n]",c[y].client_business_info);
y++;
}
void recall (Client []);
recall (c);
}
void realocate (Client c[])//Realocates memory of variable the user choses to delete.
{
int key,max=100;
printf ("\nEnter Client ID To Be Deleted:");
scanf ("%d",&key);
system ("cls");
int first = 0;
int last = max - 1;
int middle = (first+last)/2;
while( first <= last )
{
if (c[middle].client_id < key)
first = middle + 1;
else if (c[middle].client_id == key)
{
c[middle].client_id=c[middle+1].client_id;
strcpy(c[middle].client_business_name,c[middle+1].client_business_name);
strcpy(c[middle].client_first_name,c[middle+1].client_first_name);
strcpy(c[middle].client_last_name,c[middle+1].client_last_name);
strcpy(c[middle].client_address,c[middle+1].client_address);
c[middle].client_budget=c[middle+1].client_budget;
strcpy(c[middle].client_business_info,c[middle+1].client_business_info);
printf ("\nClient Removed!");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
{
printf ("\nClient Not Registered\n");
}
void recall (Client []);
recall (c);
}
void search (Client c[])//Searches for data via a Binary or Linear search.
{
int choice,max=100,ch,cho;
do{
printf ("\n1.Client ID\n2.Client Buisness Name\n3.Client First Name\n4.Client Last Name\nChoose an option to search by:");
scanf ("%d",&choice);
}while (choice<1||choice>4);
if (choice==1)//Binary Search
{
system ("cls");
int search_id1;
printf("Enter Client ID:");
scanf("%d",&search_id1);
system ("cls");
int first = 0;
int last = max - 1;
int middle = (first+last)/2;
while( first <= last )
{
if (c[middle].client_id < search_id1)
first = middle + 1;
else if (c[middle].client_id == search_id1)
{
printf ("Client ID:%d",c[middle].client_id);
printf ("\nBuisness Name:%s",c[middle].client_business_name);
printf ("\nClient First Name:%s",c[middle].client_first_name);
printf ("\nClient Last Name:%s",c[middle].client_last_name);
printf ("\nBuisness Address:%s",c[middle].client_address);
printf ("\nClient Budget:%d",c[middle].client_budget);
printf ("\nBuisness Information:%s",c[middle].client_business_info);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
{
printf("Not found!\n%d is not registered to a existing client.\n",search_id1);
}
}
else if (choice==2)//Binary Search
{
system ("cls");
char search_id2 [30];
printf("Enter Buisness Name:");
scanf(" %[^\n]",search_id2);
system ("cls");
int first = 0;
int last = max - 1;
int middle = (first+last)/2;
while( first <= last )
{
if (strcmp(c[middle].client_business_name,search_id2)<0)
first = middle + 1;
else if (strcmp(c[middle].client_business_name,search_id2)==0)
{
printf ("Client ID:%d",c[middle].client_id);
printf ("\nBuisness Name:%s",c[middle].client_business_name);
printf ("\nClient First Name:%s",c[middle].client_first_name);
printf ("\nClient Last Name:%s",c[middle].client_last_name);
printf ("\nBuisness Address:%s",c[middle].client_address);
printf ("\nClient Budget:%d",c[middle].client_budget);
printf ("\nBuisness Information:%s",c[middle].client_business_info);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
{
printf("Not found!\n%s is not a client.\n",search_id2);
}
}
else if (choice==3)//Linear Search
{
system ("cls");
char search_id3 [20];
printf("Enter Client's First Name:");
scanf(" %[^\n]",search_id3);
system ("cls");
int x=0;
while ((strcmp(c[x].client_first_name,search_id3)!=0) && x<100)
{
if (strcmp(c[x].client_first_name,search_id3)==0)
{
printf ("Client ID:%d",c[x].client_id);
printf ("\nBuisness Name:%s",c[x].client_business_name);
printf ("\nClient First Name:%s",c[x].client_first_name);
printf ("\nClient Last Name:%s",c[x].client_last_name);
printf ("\nBuisness Address:%s",c[x].client_address);
printf ("\nClient Budget:%d",c[x].client_budget);
printf ("\nBuisness Information:%s",c[x].client_business_info);
}
else if (strcmp(c[x].client_first_name,search_id3)!=0)
{
printf("Not found!\n%s is not a client.\n",search_id3);
}
x++;
}
}
else if (choice==4)//Linear Search
{
system ("cls");
char search_id4 [20];
printf("Enter Client's Last Name:");
scanf(" %[^\n]",search_id4);
system ("cls");
int y=0;
while ((strcmp(c[y].client_first_name,search_id4)!=0) && y<100)
{
if (strcmp(c[y].client_first_name,search_id4)==0)
{
printf ("Client ID:%d",c[y].client_id);
printf ("\nBuisness Name:%s",c[y].client_business_name);
printf ("\nClient First Name:%s",c[y].client_first_name);
printf ("\nClient Last Name:%s",c[y].client_last_name);
printf ("\nBuisness Address:%s",c[y].client_address);
printf ("\nClient Budget:%d",c[y].client_budget);
printf ("\nBuisness Information:%s",c[y].client_business_info);
}
else if (strcmp(c[y].client_first_name,search_id4)!=0)
{
printf("Not found!\n%s is not a client.\n",search_id4);
}
y++;
}
}
void recall (Client []);
recall (c);
}
void recall (Client c[])
{
int choice;
do{
printf ("\n\nDo You Want To:\n1.Go Back To The Main Menu\n2.Exit\n");
scanf ("%d",&choice);
}while (choice<1 || choice>2);
if (choice==1)
{
void main_menu (Client []);
main_menu (c);
}
else if (choice==2)
{
void end (Client []);
end (c);
}
}
void end (Client c[])
{
printf ("Thank You!\n");
system ("pause");
system ("cls");
}
I know this seems like a lot of code, but I am new to programming, so I wanted people's opinion on this code in C.
The main function of the program is to deal with clients.
The user can Add, Delete or change clients, or view and search for specific clients.
My main focus is to ensure that I can remove a client, as done in the reallocate function. My other main issue is the Search and sort functions. I would like to find out your opinions on the code, and what I could do to make it better.
Put the function prototypes on top
Use define MAX_CLIENTS 100 instead of typing in 100
Declare a new variable Client_Count you need this to know how many clients you have. Here I declare it as global variable. You could also declare it in main, and then carry it around like you are doing with Client
Use a function for print_client so you don't have to repeat the same code.
You might have to initialize all the clients, go from zero to MAX_CLIENTS, just set client_id to zero, so you know it's not valid or it has been deleted.
-
void main_menu(Client[]);
void accept(Client[]);
void realocate(Client[]);
void search(Client[]);
void view_sort(Client[]);
void change(Client[]);
void end(Client[]);
void recall(Client[]);
#define MAX_CLIENTS 100
int Client_Count;
int main()
{
Client_Count = 0;
Client c[MAX_CLIENTS];
main_menu(c);
system("pause");
return 0;
}
void main_menu(Client c[])//Determines what the user wants to do and grants access to one of the 6 functions.
{
int choice;
do{
printf("1.Add Client\n2.Delete Client\n3.Search Clients\n4.Change Client Information\n5.View Clients\n6.Terminate Program\nChoose an option from above:");
scanf("%d", &choice);
} while (choice < 1 || choice > 6);
system("cls");
if (choice == 1) accept(c);
if (choice == 2) realocate(c);
if (choice == 3) search(c);
if (choice == 4) change(c);
//if (choice == 5) view_sort(c);
if (choice == 6) end(c);
}
void accept(Client c[])//Accepts data from the user.
{
if (Client_Count < MAX_CLIENTS)
{
printf("\nEnter Client ID:");
scanf("%d", &c[Client_Count].client_id);
printf("Enter Buisness Name:");
scanf(" %[^\n]", c[Client_Count].client_business_name);
printf("Enter Client First Name:");
scanf(" %[^\n]", c[Client_Count].client_first_name);
printf("Enter Client Last Name:");
scanf(" %[^\n]", c[Client_Count].client_last_name);
printf("Enter Buisness Address:");
scanf(" %[^\n]", c[Client_Count].client_address);
printf("Enter Client Budget:");
scanf("%f", &c[Client_Count].client_budget);
printf("Enter Buisness Information:");
scanf(" %[^\n]", c[Client_Count].client_business_info);
Client_Count++;
}
else
{
printf("too many\n");
}
recall(c);
}
void print_client(Client *c)
{
printf("Client ID:%d", c->client_id);
printf("\nBuisness Name:%s", c->client_business_name);
printf("\nClient First Name:%s", c->client_first_name);
printf("\nClient Last Name:%s", c->client_last_name);
printf("\nBuisness Address:%s", c->client_address);
printf("\nClient Budget:%d", c->client_budget);
printf("\nBuisness Information:%s", c->client_business_info);
}
void search(Client c[])//Searches for data via a Binary or Linear search.
{
int choice = 0;//initialize
do{
printf("\n1.Client ID\n2.Client Buisness Name\n3.Client First Name\n4.Client Last Name\nChoose an option to search by:");
scanf("%d", &choice);
} while (choice < 1 || choice > 4);
system("cls");
if (choice == 1)//Binary Search
{
int search_id1;
printf("Enter Client ID:");
scanf("%d", &search_id1);
system("cls");
for (int i = 0; i < Client_Count; i++)
{
if (c[i].client_id == search_id1)
{
print_client(&c[i]);
return;
}
}
printf("Not found!\n%d is not registered to a existing client.\n", search_id1);
}
else if (choice == 2)//Binary Search
{
system("cls");
char search_id2[30];
printf("Enter Buisness Name:");
scanf(" %[^\n]", search_id2);
for (int i = 0; i < Client_Count; i++)
{
if (strcmp(c[i].client_business_name, search_id2) == 0)
{
print_client(&c[i]);
return;
}
}
printf("Not found!\n%s is not a client.\n", search_id2);
}
//...
recall(c);
}