How to implement stacks using a structure while scanning from a file - c

#include <stdio.h>
#include <string.h>
typedef struct
{
int client_id;
char business_name [30];
char client_first_name [20];
char client_last_name [20];
char address [40];
float budget;
float energy_requirements;
char business_info [300];
}Client;
main()
{
Client c[20];
FILE*z;
void initialise (FILE*,Client []);
initialise (z,c);
system ("PAUSE");
}
void initialise(FILE*z,Client c[])
{
int x,max=20,top=-1;
if (top==max-1)
{
return;
}
top++;
for (x=0;x<20;x++)//Assigns all places in the structure to -1 and NULL
{
c[x].client_id=-1;
strcpy(c[x].business_name,"NULL");
strcpy(c[x].client_first_name,"NULL");
strcpy(c[x].client_last_name,"NULL");
strcpy(c[x].address,"NULL");
c[x].budget=-1;
c[x].energy_requirements=-1;
strcpy(c[x].business_info,"NULL");
}
z=fopen ("Novus.txt","r");
for (x=0;x<20;x++)//Replaces values in structure with data from text file
{
fscanf (z,"%d\n %[^\n]\n %[^\n]\n %[^\n]\n %[^\n]\n%f\n%f\n %[^\n]\n\n",&c[x].client_id,c[x].business_name,c[x].client_first_name,c[x].address,&c[x].budget,&c[x].energy_requirements,c[x].business_info);
}
fclose (z);
void menu (FILE*,Client []);
menu (z,c);
}
void menu (FILE*z,Client c[])
{
int choice;
do{
printf ("1.Add Client\n2.Change Client Information\n3.Delete Client\n4.Search Client\n5.Calculate Energy Requirements\n6.View Clients\n7.Terminate Program\nChoose an option from above:");
scanf ("%d",&choice);
}while (choice<1||choice>7);
if (choice==1)
{
system ("cls");
void accept (FILE*,Client []);
accept (z,c);
}
if (choice==2)
{
system ("cls");
void change (FILE*,Client []);
change (z,c);
}
if (choice==3)
{
system ("cls");
void destroy (FILE*,Client []);
destroy (z,c);
}
if (choice==4)
{
system ("cls");
void search (FILE*,Client []);
search (z,c);
}
if (choice==5)
{
system ("cls");
void energy (FILE*,Client []);
energy (z,c);
}
if (choice==6)
{
system ("cls");
void view (FILE*,Client []);
view (z,c);
}
if (choice==7)
{
system ("cls");
void end (FILE*,Client []);
end (z,c);
}
}
void accept (FILE*z,Client c[])//Accepts data from the user.
{
int max=20,top=-1;
int y=0,num,choice,choice2;
if (top==max-1)
{
return;
}
top++;
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].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].address);
printf ("Enter Client Budget:");
scanf ("%f",&c[y].budget);
printf ("Enter Client Energy Requirements:");
scanf ("%f",&c[y].energy_requirements);
printf ("Enter Buisness Information:");
scanf (" %[^\n]",c[y].business_info);
y++;
}
do {//Asks the user if they want to enter more data or terminate program.
printf ("\n\nDo You Want To:\n1.EnterMore Clients\n2.Continue\n");
scanf ("%d",&choice);
}while (choice<1 || choice>2);
if (choice==1)
{
void accept (Client []);
accept (c);
}
else if (choice==2)
{
do{
printf ("\n\nDo You Want To:\n1.Go Back To The Main Menu\n2.Exit\n");
scanf ("%d",&choice2);
}while (choice2<1 || choice2>2);
if (choice2==1)
{
void menu (Client[]);
menu (c);
}
else if (choice2==2)
{
void end (FILE*,Client []);
end (z,c);
}
}
}
I just wanted to find out if I am properly pushing data to the stack, and if I can scan the information from the file to the stack using the method above.
What I wanted to do was design a structure that can be used as a stack, and that can be populated using a pop function, such as that used in the initialise function. What my question is, is that I am fairly new to using stacks, and some times when I try to run my program using stacks, my antivirus program, Kaspersky, detects it as a Trojan Horse. What I wanted to know, is if I am implementing the stack correctly.

All errors have been addressed up to the point where you need to define the funcitons called in menu, etc... When building, make sure warnings are enabled gcc -Wall -Wextra -o yourprogram yourprogram.c at a minimum. In addition to the comment above, I have included comments inline below where attention is first needed. I have also provided the results of the current compile following the code. Finish defining the needed functions and then edit your question above and include any new problems you have run into. Good luck:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int client_id;
char business_name[30];
char client_first_name[20];
char client_last_name[20];
char address[40];
float budget;
float energy_requirements;
char business_info[300];
} Client;
int main () {
Client c[20];
FILE *z;
void initialise (FILE *, Client[]);
initialise (z, c);
system ("PAUSE");
return 0;
}
void initialise (FILE * z, Client c[]) {
int x;
int max = 20;
int top = -1;
if (top == (max - 1)) {
return;
}
top++;
for (x = 0; x < 20; x++) //Assigns all places in the structure to -1 and NULL
{
c[x].client_id = -1;
strcpy (c[x].business_name, "NULL");
strcpy (c[x].client_first_name, "NULL");
strcpy (c[x].client_last_name, "NULL");
strcpy (c[x].address, "NULL");
c[x].budget = -1;
c[x].energy_requirements = -1;
strcpy (c[x].business_info, "NULL");
}
z = fopen ("Novus.txt", "r");
for (x = 0; x < 20; x++) //Replaces values in structure with data from text file
{
fscanf (z,
"%d %[^\n]s %[^\n]s %[^\n]s %f %f %[^\n]s", /* format may need further help */
&c[x].client_id, c[x].business_name, c[x].client_first_name,
c[x].address, &c[x].budget, &c[x].energy_requirements,
c[x].business_info);
}
fclose (z);
void menu (FILE *, Client[]); /* must be previously declared/defined */
menu (z, c); /* you just closed 'z' two line up ?? */
}
void menu (FILE * z, Client c[]) {
int choice;
do {
printf
("1.Add Client\n2.Change Client Information\n3.Delete Client\n4.Search Client\n5.Calculate Energy Requirements\n6.View Clients\n7.Terminate Program\nChoose an option from above:");
scanf ("%d", &choice);
} while (choice < 1 || choice > 7);
if (choice == 1) {
system ("cls");
void accept (FILE *, Client[]); /* must be previously declared/defined */
accept (z, c);
}
if (choice == 2) {
system ("cls");
void change (FILE *, Client[]); /* must be previously declared/defined */
change (z, c);
}
if (choice == 3) {
system ("cls");
void destroy (FILE *, Client[]); /* must be previously declared/defined */
destroy (z, c);
}
if (choice == 4) {
system ("cls");
void search (FILE *, Client[]); /* must be previously declared/defined */
search (z, c);
}
if (choice == 5) {
system ("cls");
void energy (FILE *, Client[]); /* must be previously declared/defined */
energy (z, c);
}
if (choice == 6) {
system ("cls");
void view (FILE *, Client[]); /* must be previously declared/defined */
view (z, c);
}
if (choice == 7) {
system ("cls");
void end (FILE *, Client[]); /* must be previously declared/defined */
end (z, c);
}
}
void accept (FILE * z, Client c[]) //Accepts data from the user.
{
int max = 20;
int top = -1;
int y = 0, num, choice, choice2;
if (top == (max - 1)) {
return;
}
top++;
printf ("How Many Clients Do You Want To Add:");
scanf ("%d", &num); /* with multiple uses of scanf, you will need to flush the input buffer to */
system ("cls"); /* eliminate remaining '\n' chars that remain after the user presses 'Enter' */
while (y < num) { /* a simple 'int c;... do {c = getchar();} while (c != '\n'); after each scanf */
printf ("\nEnter Client ID:"); /* will suffice. (note 'c' is declared as an 'int' */
scanf ("%d", &c[y].client_id);
printf ("Enter Buisness Name:");
scanf (" %[^\n]", c[y].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].address);
printf ("Enter Client Budget:");
scanf ("%f", &c[y].budget);
printf ("Enter Client Energy Requirements:");
scanf ("%f", &c[y].energy_requirements);
printf ("Enter Buisness Information:");
scanf (" %[^\n]", c[y].business_info);
y++;
}
do { //Asks the user if they want to enter more data or terminate program.
printf ("\n\nDo You Want To:\n1.EnterMore Clients\n2.Continue\n");
scanf ("%d", &choice);
} while (choice < 1 || choice > 2);
if (choice == 1) {
accept (z, c);
} else if (choice == 2) {
do {
printf
("\n\nDo You Want To:\n1.Go Back To The Main Menu\n2.Exit\n");
scanf ("%d", &choice2);
} while (choice2 < 1 || choice2 > 2);
if (choice2 == 1) {
menu (z, c);
} else if (choice2 == 2) {
end (z, c);
}
}
}
Current Compiler Errors:
$ gcc -Wall -Wextra -o bin/addrstack addrstack.c
addrstack.c: In function ‘accept’:
addrstack.c:148:17: warning: implicit declaration of function ‘end’ [-Wimplicit-function-declaration]
end (z, c);
^
addrstack.c:97:18: note: previous declaration of ‘end’ was here
void end (FILE *, Client[]); /* must be previously declared/defined */
^
addrstack.c:148:17: error: incompatible implicit declaration of function ‘end’
end (z, c);
^
addrstack.c:97:18: note: previous implicit declaration of ‘end’ was here
void end (FILE *, Client[]); /* must be previously declared/defined */

I use the following codes for generic stack for any type.
In the example, I create a stack of int. Yet you can typedef your type to a name, and use DeclareStackType(YourType) to declare a data structure for the stack, and then use stack__YourType foo; to declare the stack. See test code for detail.
#include <malloc.h>
#define DeclareStackType(ValueType) \
typedef struct { \
int size; \
ValueType *buf; \
int index; \
} stack_ ## ValueType
#define InitStack(stack, ValueType, sz) do {stack.size = sz; stack.buf=(ValueType*)malloc(sizeof(ValueType)*sz); stack.index = 0;} while (0)
// this re-uses the already initialized buffer. Just reset index to zero.
#define ClearStack(stack) do {stack.index = 0;} while(0)
#define PushStack(stack, value) do {stack.buf[stack.index++] = value; } while(0)
#define PopStack(stack) (stack.buf[--stack.index])
#define IsStackFull(stack) (stack.index == stack.size)
#define IsStackEmpty(stack) (stack.index == 0)
#define PushStackSafe(stack, value) do {if (!IsStackFull(stack)) stack.buf[stack.index++] = value;} while(0)
#define PopStackSafe(stack) (stack.buf[IsStackEmpty(stack)? 0 : (stack.index -= 1)])
// -------- test codes (in C++, since C++ can compile C program, I am lazy to do C printf...)---------------
#include <iostream>
DeclareStackType(int);
stack_int my_integer_stack;
using namespace std;
int main(int argc, char *argv[])
{
InitStack(my_integer_stack, int, 5);
if (IsStackEmpty(my_integer_stack)) {
cout << "1. stack empty now" << endl;
}
PushStack(my_integer_stack, 1);
PushStack(my_integer_stack, 2);
ClearStack(my_integer_stack); // clear the above input
if (IsStackEmpty(my_integer_stack)) {
cout << "2. stack empty now" << endl;
}
PushStack(my_integer_stack, 3);
PushStack(my_integer_stack, 5);
PushStack(my_integer_stack, 1);
PushStack(my_integer_stack, 2);
PushStackSafe(my_integer_stack, 8);
if (IsStackFull(my_integer_stack)) {
cout << "3. stack full now" << endl;
}
PushStackSafe(my_integer_stack, 9); // won't push
cout << PopStack(my_integer_stack) << endl;
cout << PopStack(my_integer_stack) << endl;
cout << PopStack(my_integer_stack) << endl;
cout << PopStack(my_integer_stack) << endl;
cout << PopStack(my_integer_stack) << endl;
if (IsStackEmpty(my_integer_stack)) {
cout << "4. stack empty now" << endl;
}
cout << PopStackSafe(my_integer_stack) << endl; // pop will not go to index -1, yet it returns buf[0] in the stack
}

Related

Displaying structs

This program is meant to display a video game inventory based off of the user's input. The user needs to determine how long the loop runs with num_of_games. We have to use a switch loop to determine the genre. It compiles but it does not display correctly.
#include <stdio.h>
#include <string.h>
#define MAX 16
typedef enum genre_type{ action = 0, rpg = 1, simulation = 2,
strategy = 3, sports = 4} genre_t;
typedef struct{
char title[MAX];
int num_sold;
genre_t genre;
}game_s;
// suppose to use functions and enum list for determining the genre
void get_game_info(game_s *ptr);
void display_inventory(game_s game[], int num_of_games);
int
main(void){
int i=0, num_of_games;
int c_game=0;
game_s game[num_of_games];
printf("How many games are there in inventory? ");
scanf("%d", &num_of_games);
fflush(stdin);
printf("\n");
while(c_game < num_of_games){
printf("\n");
get_game_info(&game[c_game]);
c_game++;
}
printf("\n");
display_inventory(game, num_of_games);
return(0);
}
void get_game_info(game_s *ptr)
{
int i, str_len, genre, num_sold;
printf("Title of game <maximum of 15 characters>: ");
gets(ptr->title);
str_len = strlen(ptr->title);
if(str_len >= 15){
printf("Title will be truncated\n");
ptr->title[MAX]= '\0';
}
printf("Number sold: ");
scanf("%d", &ptr->num_sold);
fflush(stdin);
printf("Genre (0-action, 1-rpg, 2-simulation, 3-strategy, 4-sports): ");
scanf("%d", &ptr->genre);
fflush(stdin);
if(ptr->genre>4){
printf("Not a valid genre");
fflush(stdin);
}
}
void display_inventory(game_s game[], int num_of_games)
{
int i, genre;
printf("Title\t\t\t\t\t\tQuantity Sold\t\t\t\t\t\tGenre");
printf("\n=====\t\t\t\t\t\t=============\t\t\t\t\t\t=====\n");
for(i=0; i < num_of_games; i++){
switch(genre){
case action: printf("Action"); break;
case rpg: printf("RPG"); break;
case simulation: printf("Simulation"); break;
case strategy: printf("Strategy"); break;
case sports: printf("Sports"); break;
default: puts("Not a choice. Try again"); break;
I think this is the thing that is causing most of the problem. I don't know if I am calling the struct right with the game[I].title and others.
the problem is with the struct calls I think. If I use game_s[I].title I get "expected expression before" error and if I use game[I].title it doesn't print properly
printf("%s\t\t\t\t\t\t%d\t\t\t\t\t\t%s", game[i].title, game[i].num_sold, game[i].genre);
printf("\n");
}
}
}
I think the problem is game_s game[num_of_games]; because num_of_games isn't initiate.
It should be:
printf("How many games are there in inventory? ");
scanf("%d", &num_of_games);
game_s * game_s game = (game_s *) malloc(num_of_games * sizeof(game_s));
Your effort is commendable. You provide code and a good-faith attempt to understand why things don't work, but unfortunately, your code was riddled with errors. Not the least of which was your almost immediate invocation of Undefined Behavior by attempting to declare a VLA with an uninitialized num_of_games. No matter what you did in your code from that point forward, it was nothing but a dice-roll whether you actually processed something or SegFaulted.
Your lack of output in display_inventory (regardless what was actually in memory) is due the placement of your printf statements within the body of the switch statement. When you break from a switch you don't just jump below the default case, you jump out of the switch completely. So even if the rest of your code was correct, you would never produce output.
fflush(stdin) is wrong and invokes undefined behavior on all but windoze. It is only defined for seekable streams for the rest of the world -- don't use it. Instead, you can define a simple function to empty stdin and call it as required instead.
When you compile, always compile with compiler warnings enabled, and do not accept code until it compiles cleanly without warning. To enable warnings add -Wall -Wextra to your gcc compile string. (add -pedantic for several additional warnings). For VS (cl.exe on windoze), add /Wall. For clang, add -Weverything. Read and understand each warning. They will identify any problems, and the exact line on which they occur. You can learn as much about coding by simply listening to what your compiler is telling you as you can from most tutorials.
The number of errors in your code are too voluminous to itemize and speak to every point, so I have included comments inline below addressing the errors.
#include <stdio.h>
#include <stdlib.h> /* for EXIT_FAILURE */
#include <string.h>
#define MAX 16
typedef enum genre_type {
action = 0,
rpg = 1,
simulation = 2,
strategy = 3,
sports = 4
} genre_t;
typedef struct {
char title[MAX];
int num_sold;
genre_t genre;
} game_s;
// suppose to use functions and enum list for determining the genre
void get_game_info (game_s *ptr);
void display_inventory (game_s *game, int num_of_games);
void fflush_stdin();
int main (void) {
int num_of_games,
c_game = 0,
scnfrtn; /* scanf return - must always check EOF */
printf ("How many games are there in inventory? ");
for (;;) { /* loop until valid input or EOF (user cancels) */
if ((scnfrtn = scanf ("%d", &num_of_games)) == 1) {
fflush_stdin(); /* manually empty stdin */
break;
}
else if (scnfrtn == EOF) { /* user cancels? */
fprintf (stderr, "user canceled input.\n");
exit (EXIT_FAILURE);
}
/* handle error */
fprintf (stderr, "error: invalid input.\n");
fflush_stdin();
}
putchar ('\n'); /* don't printf a single-char */
/* declare VLA only AFTER num_of_games has a value */
game_s game[num_of_games];
memset (game, 0, sizeof game); /* optional, zero VLA */
while (c_game < num_of_games) {
putchar ('\n');
get_game_info (&game[c_game]);
c_game++;
}
putchar ('\n');
display_inventory (game, num_of_games);
return 0;
}
void get_game_info (game_s *ptr)
{
int scnfrtn; /* scanf return - must always check EOF */
size_t len = 0; /* strlen return is size_t */
printf ("Title of game <maximum of 15 characters>: ");
fgets (ptr->title, MAX, stdin); /* NEVER, NEVER, NEVER use gets */
len = strlen (ptr->title);
if (len && ptr->title[len-1] == '\n') /* check for trailing \n */
ptr->title[--len] = '\0'; /* overwrite with nul-character */
else /* warn of truncation */
fprintf (stderr, "error: title too long, truncated.\n");
for (;;) { /* loop until valid input or EOF (user cancels) */
printf ("Number sold: ");
if ((scnfrtn = scanf ("%d", &ptr->num_sold)) == 1) {
fflush_stdin();
break;
}
else if (scnfrtn == EOF) {
fprintf (stderr, "user canceled input.\n");
exit (EXIT_FAILURE);
}
fprintf (stderr, "error: invalid input.\n");
fflush_stdin();
}
for (;;) { /* loop until valid input or EOF (user cancels) */
printf ("Genre (0-action, 1-rpg, 2-simulation, "
"3-strategy, 4-sports): ");
if ((scnfrtn = scanf ("%d", (int*)&ptr->genre)) == 1) {
fflush_stdin();
break;
}
else if (scnfrtn == EOF) {
fprintf (stderr, "user canceled input.\n");
exit (EXIT_FAILURE);
}
else if (ptr->genre > 4) /* additional check for genre */
fprintf (stderr, "error: invalid genre.\n");
else
fprintf (stderr, "error: invalid input.\n");
fflush_stdin();
}
}
void display_inventory (game_s *game, int num_of_games)
{
int i;
printf ("%11s%-24s %-24s %s\n========================="
"==============================================\n",
" ", "Title","Quantity Sold", "Genre");
for (i = 0; i < num_of_games; i++) {
switch (game[i].genre) {
case action:
printf ("%-11s", "Action");
break;
case rpg:
printf ("%-11s", "RPG");
break;
case simulation:
printf ("%-11s", "Simulation");
break;
case strategy:
printf ("%-11s", "Strategy");
break;
case sports:
printf ("%-11s", "Sports");
break;
default:
puts ("Not a choice. Try again");
break;
}
printf ("%-24s %-24u %d\n", game[i].title,
game[i].num_sold, game[i].genre);
}
}
void fflush_stdin()
{
for (int c = getchar(); c != '\n' && c != EOF; c = getchar()) {}
}
(note: use printf minimum field with modifier to control spacing instead of a bunch of tabs smushed together)
Example Use/Output
$ ./bin/gamegenre
How many games are there in inventory? 3
Title of game <maximum of 15 characters>: first title
Number sold: 12
Genre (0-action, 1-rpg, 2-simulation, 3-strategy, 4-sports): 2
Title of game <maximum of 15 characters>: second title
Number sold: 13
Genre (0-action, 1-rpg, 2-simulation, 3-strategy, 4-sports): 1
Title of game <maximum of 15 characters>: third title
Number sold: 14
Genre (0-action, 1-rpg, 2-simulation, 3-strategy, 4-sports): 3
Title Quantity Sold Genre
=======================================================================
Simulation first title 12 2
RPG second title 13 1
Strategy third title 14 3
(note: I didn't know where you intended your genre descriptions to go, so they are simply output at the beginning of each line above)
Look things over and let me know if you have further questions.

Restaurant Program, when repeating, skips the first inputs

new to programming here :3
(Don't check my profile, I actually only know C, for now...)
I need help here, I dunno what's causing the problem, but whenever I repeat the program, it skips asking for a replacement value in
char C1.name
in function
void Name()
{
p("ENTER NAME: ");
gets(C1.name);
p("CONTACT DETAILS: ");
s("%d", &C1.cont_no);
}
in my Program
#include <stdio.h>
#include <windows.h>
#define p printf
#define s scanf
void Name();
void Order();
void Total();
void Receipt();
char Repeat();
/* CUSTOMER DETAILS */
struct CustomerOrder
{
char name[50];
long int cont_no;
int qty;
float price, total;
} C1;
main()
{
char cont;
/* Program Process... */
do{
Name();
Order();
Total();
Receipt();
cont = Repeat();
}while(cont == 'Y');
}
void Name()
{
/* ENTER NAME AND CONTACT DETAILS */
p("ENTER NAME: ");
gets(C1.name);
p("CONTACT DETAILS: ");
s("%d", &C1.cont_no);
}
void Order()
{
/* ENTER ORDERS */
p("HOW MANY ORDERS: ");
s("%d", &C1.qty);
C1.price = 59.99;
}
void Total()
{
/* TOTAL */
C1.total = C1.price * C1.qty;
p("TOTAL IS: %.2f", C1.total);
system("pause");
}
void Receipt()
{
system("cls");
/*PRINTED RECEIPT SAMPLE */
p("NAME IS: %s\n", C1.name);
p("CONTACT DETAILS: %d\n", C1.cont_no);
p("QTY: %d\n", &C1.qty);
p("PRICE EACH: %.2f\n", C1.price);
p("TOTAL PAYOUT: %.2f\n", C1.total);
}
char Repeat()
{
/* ASKS USER TO REPEAT PROGRAM, THEN RETURN VALUE TO BE USED BY function
main */
char repeat;
p("REPEAT?: ");
s("%s", &repeat);
return repeat;
}
There may be other problems you would probably notice (which I dunno if there are, but I would like it NOT to skip the Name part and stuff...
You only want to get a character when asking the user to repeat so change
s("%s", &repeat);
to
s(" %c", &repeat);
if you add a space ^ you will skip the \n that you entered previously.

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);
}
}

How do I add a contact to a phonebook program in C?

For my intro to programming class, we have to code a phonebook in C that lets users add contacts, as well as delete and display them. It also has to allocate and free memory as necessary (I tried to do this, but I honestly don't really know what I'm doing).
Anyway, I cannot figure out how to add a contact to the phonebook. I've pasted the relevant part of the program so far. It compiles, but it crashes every time I try to add a contact. Once I get this figured out, I think I can get the rest of the functions without too much trouble. If anyone could help me out, I'd really appreciate it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct entry {
char fname[20];
char lname[20];
char pnumber[20];
} entry;
// function prototypes
void addentry(int, entry*, char addfname[20], char addlname[20], char addpnumber[20]);
main() {
int selection = 0;
int inputtest = 1;
int pnum = 0; // keeps track of number of contacts
char addfname[20] = { '\0' };
char addlname[20] = { '\0' };
char addpnumber[20] = { '\0' };
entry *pcontacts;
pcontacts = (entry*)calloc(1, (sizeof(entry)));
if (pcontacts == NULL) {
printf("No memory is available.");
free(pcontacts);
return 0;
}
while (1) {
do {
printf("\nPhonebook Menu\n\n");
printf("1:\tAdd contact\n");
printf("2:\tDelete contact\n");
printf("3:\tDisplay contacts\n");
printf("4:\tExit\n");
printf("\nChoose an action (1-4): ");
scanf("%d", &selection);
if (selection < 1 || selection > 4) {
printf("Invalid input. Please enter an integer between 1 and 4.\n");
inputtest = 0;
}
if (selection == 4) {
free(pcontacts);
printf("\nThank you for using this phonebook.");
return 0;
}
switch (selection) {
case 1:
pnum++;
printf("\nEnter first name: ");
scanf("%s", addfname);
printf("Enter last name: ");
scanf("%s", addlname);
printf("Enter phone number (no spaces): ");
scanf("%s", addpnumber);
addentry(pnum, pcontacts, addfname[20], addlname[20], addpnumber[20]);
break;
}
} while (inputtest == 1);
}
}
void addentry(int pnum, entry *pcontacts, char addfname[20], char addlname[20], char pnumber[20]) {
pcontacts = (entry*)malloc(pnum * (sizeof(entry)));
if (pcontacts != NULL) {
strcpy(*pcontacts[pnum - 1].fname, addfname);
printf("\nContact has been added.");
} else {
printf ("No memory is available.\n");
}
}
You get strings from standard input with scanf, but you should tell scanf the maximum number of bytes to store to the destination arrays to avoid buffer overruns:
scanf("%19s", addfname);
...
scanf("%19s", addlname);
...
scanf("%19s", addpnumber);
The way you call addentry is incorrect:
addentry(pnum, pcontacts, addfname[20], addlname[20], addpnumber[20]);
You actually try to read the byte just after the end of addfname, addlname and addpnumber. You should instead pass the arrays themselves, that will be passed to the function addentry as pointers to their first bytes:
addentry(pnum, pcontacts, addfname, addlname, addpnumber);
addentry should reallocate the array with realloc. It should be passed a pointer to the array pointer to it can update the pointer in main.
addentry does not copy the strings correctly: it only copies one, but with a syntax error.
Here is a corrected version:
void addentry(int, entry**, char addfname[20], char addlname[20], char addpnumber[20]);
int main(void) {
int selection = 0;
int inputtest = 1;
int pnum = 0; // keeps track of number of contacts
char addfname[20];
char addlname[20];
char addpnumber[20];
entry *pcontacts = NULL;
for (;;) {
do {
printf("\nPhonebook Menu\n\n");
printf("1:\tAdd contact\n");
printf("2:\tDelete contact\n");
printf("3:\tDisplay contacts\n");
printf("4:\tExit\n");
printf("\nChoose an action (1-4): ");
scanf("%d", &selection);
if (selection < 1 || selection > 4) {
printf("Invalid input. Please enter an integer between 1 and 4.\n");
inputtest = 0;
}
if (selection == 4) {
free(pcontacts); /* OK for NULL */
printf("\nThank you for using this phonebook.");
return 0;
}
switch (selection) {
case 1:
printf("\nEnter first name: ");
scanf("%19s", addfname);
printf("Enter last name: ");
scanf("%19s", addlname);
printf("Enter phone number (no spaces): ");
scanf("%19s", addpnumber);
addentry(pnum, &pcontacts, addfname, addlname, addpnumber);
pnum++;
break;
}
} while (inputtest == 1);
}
}
/* add an entry at position pnum */
void addentry(int pnum, entry **pp, char addfname[20], char addlname[20], char pnumber[20]) {
entry *pcontact = *pp;
pcontacts = realloc(pcontacts, (pnum + 1) * sizeof(entry));
if (pcontacts != NULL) {
*pp = pcontacts; /* update pointer in main */
strcpy(pcontacts[pnum].fname, addfname);
strcpy(pcontacts[pnum].lname, addlname);
strcpy(pcontacts[pnum].pnumber, addpnumber);
printf("\nContact has been added.");
} else {
printf ("No memory is available.\n");
}
}

Optimizing Code & Opinions

#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);
}

Resources