Print data from list with condition - c

I need to make a function that only prints data for a certain month and year (see case 2 and void printList(LIST*pFirst, int pm, int py)), but it seems I'm doing something wrong, as the whole program crashes:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
#define MAX_LENGTH 80
#define LOOPS 1
struct delivery
{
int num;
char name[20];
char code[8];
char info[80];
int day;
int month;
int year;
int amount;
};
typedef struct delivery BODY;
struct List{
BODY body;
struct List*pNext;
};
typedef struct List LIST;
int enterBody(BODY*ps);
void printBody(BODY s);
void printList(LIST*pFirst, int pm, int py);
LIST*insertBegin(LIST*pFirst, BODY newBody);
int main()
{
FILE*pOut = NULL, *pIn = NULL;
char Fname[] = "List_bin.dat";
BODY newbody;
LIST*pFirst = NULL, *p;
int res, i, mode, pm, py;
char sfn[20], gr[20];
int newgr, fn;
BODY delivery;
char*menu[] = { "MENU:",
"1 - Enter info for new delivery ",
"2 - Print info for deliveries for an entered month ",
};
do
{
system("cls");
for (i = 0; i < 3; i++)
printf("\n%s\n", menu[i]);
do
{
fflush(stdin);
printf("\nChoose operation (1-2): ");
res = scanf("%d", &mode);
} while (res != 1);
switch (mode)
{
case 1:
for (i = 0; i < LOOPS; i++)
{
res = enterBody(&delivery);
if (res != 1)
{
printf("Error in initialization %d\n", res);
break;
}
p = insertBegin(pFirst, delivery);
if (p == NULL)
{
printf("Not enough memory! ");
break;
}
pFirst = p;
}
system("pause");
break;
case 2:
printf("\nEnter month: ");
scanf("%19s", pm);
printf("\nEnter year: ");
scanf("%19s", py);
if (pFirst != NULL)
{
printList(pFirst, pm, py);
}
else printf("\nEmpty list!\n");
system("pause");
break;
default:
printf("\nIncorrect operation!\n");
system("pause");
}
} while (mode != 11);
system("pause");
return 0;
}
int enterBody(BODY*ps)
{
if (ps == NULL) return 0;
memset(ps, 0, sizeof(BODY));
fflush(stdin);
printf("\nEnter delivery number: ");
scanf("%d", &(ps->num));
fflush(stdin);
printf("\nEnter name of product: ");
gets(ps->name);
printf("\nEnter provider code: ");
gets(ps->code);
printf("\nEnter provider's company, address and phone number: ");
gets(ps->info);
printf("\nEnter date: ");
scanf("%d", &(ps->day));
fflush(stdin);
printf("\nEnter month: ");
scanf("%d", &(ps->month));
fflush(stdin);
printf("\nEnter year: ");
scanf("%d", &(ps->year));
fflush(stdin);
printf("\nEnter amount delivered: ");
scanf("%d", &(ps->amount));
fflush(stdin);
return 1;
}
void printBody(BODY s)
{
printf("\nNumber: %d\tName: %s\tCode: %s\tInfo: %s\nDate: %d-%d-%d\tAmount: %d",
s.num, s.name, s.code, s.info, s.day, s.month, s.year, s.amount);;
}
void printList(LIST*pFirst, int pm, int py)
{
LIST*p = NULL;
if(strcmp(p->body.month, pm) == 0)
p = pFirst;
while (p != NULL)
{
printBody(p->body);
p = p->pNext;
}
printf("\n");
}
LIST*insertBegin(LIST*pFirst, BODY newBody)
{
LIST*p;
p = (LIST*)malloc(sizeof(LIST));
if (p == NULL)
{
printf("Not enough memory\n");
return NULL;
}
else
{
p->body = newBody;
p->pNext = pFirst;
pFirst = p;
return p;
}
}

You only need 2 small changes to make the program not crash for case 2. You are scanning the wrong type for a digit, you should use %d and a pointer to an int. And when printing the list, you need to start from the beginning.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
#define MAX_LENGTH 80
#define LOOPS 1
struct delivery
{
int num;
char name[20];
char code[8];
char info[80];
int day;
int month;
int year;
int amount;
};
typedef struct delivery BODY;
struct List{
BODY body;
struct List*pNext;
};
typedef struct List LIST;
int enterBody(BODY*ps);
void printBody(BODY s);
void printList(LIST*pFirst, int pm, int py);
LIST*insertBegin(LIST*pFirst, BODY newBody);
int main()
{
FILE*pOut = NULL, *pIn = NULL;
char Fname[] = "List_bin.dat";
BODY newbody;
LIST*pFirst = NULL, *p;
int res, i, mode, pm, py;
char sfn[20], gr[20];
int newgr, fn;
BODY delivery;
char*menu[] = { "MENU:",
"1 - Enter info for new delivery ",
"2 - Print info for deliveries for an entered month ",
};
do
{
system("cls");
for (i = 0; i < 3; i++)
printf("\n%s\n", menu[i]);
do
{
fflush(stdin);
printf("\nChoose operation (1-2): ");
res = scanf("%d", &mode);
} while (res != 1);
switch (mode)
{
case 1:
for (i = 0; i < LOOPS; i++)
{
res = enterBody(&delivery);
if (res != 1)
{
printf("Error in initialization %d\n", res);
break;
}
p = insertBegin(pFirst, delivery);
if (p == NULL)
{
printf("Not enough memory! ");
break;
}
pFirst = p;
}
system("pause");
break;
case 2:
printf("\nEnter month: ");
scanf("%d", &pm);
printf("\nEnter year: ");
scanf("%d", &py);
if (pFirst != NULL)
{
printList(pFirst, pm, py);
}
else printf("\nEmpty list!\n");
system("pause");
break;
default:
printf("\nIncorrect operation!\n");
system("pause");
}
} while (mode != 11);
system("pause");
return 0;
}
int enterBody(BODY*ps)
{
if (ps == NULL) return 0;
memset(ps, 0, sizeof(BODY));
fflush(stdin);
printf("\nEnter delivery number: ");
scanf("%d", &(ps->num));
fflush(stdin);
printf("\nEnter name of product: ");
gets(ps->name);
printf("\nEnter provider code: ");
gets(ps->code);
printf("\nEnter provider's company, address and phone number: ");
gets(ps->info);
printf("\nEnter date: ");
scanf("%d", &(ps->day));
fflush(stdin);
printf("\nEnter month: ");
scanf("%d", &(ps->month));
fflush(stdin);
printf("\nEnter year: ");
scanf("%d", &(ps->year));
fflush(stdin);
printf("\nEnter amount delivered: ");
scanf("%d", &(ps->amount));
fflush(stdin);
return 1;
}
void printBody(BODY s)
{
printf("\nNumber: %d\tName: %s\tCode: %s\tInfo: %s\nDate: %d-%d-%d\tAmount: %d",
s.num, s.name, s.code, s.info, s.day, s.month, s.year, s.amount);;
}
void printList(LIST*pFirst, int pm, int py)
{
LIST*p = NULL;
p = pFirst;
while (p != NULL)
{
printBody(p->body);
p = p->pNext;
}
printf("\n");
}
LIST*insertBegin(LIST*pFirst, BODY newBody)
{
LIST*p;
p = (LIST*)malloc(sizeof(LIST));
if (p == NULL)
{
printf("Not enough memory\n");
return NULL;
}
else
{
p->body = newBody;
p->pNext = pFirst;
pFirst = p;
return p;
}
}
Test
MENU:
1 - Enter info for new delivery
2 - Print info for deliveries for an entered month
Choose operation (1-2): 1
Enter delivery number: 2
Enter name of product:
Enter provider code: 2
Enter provider's company, address and phone number: 2
Enter date: 2
Enter month: 2
Enter year: 2
Enter amount delivered: 2
sh: 1: pause: not found
sh: 1: cls: not found
MENU:
1 - Enter info for new delivery
2 - Print info for deliveries for an entered month
Choose operation (1-2): 2
Enter month: 2
Enter year: 2
Number: 2 Name: Code: 2 Info: 2
Date: 2-2-2 Amount: 2

Related

Get first letter from C string

I have a program in C which is basically a contact book, and I've already done all the functionalities (add contact, delete etc) but I also have to implement a way to search for contacts by the initial letter (the user type any letter, and if they exist contacts that start with that letter they should be displayed) but I'm not getting the first letter of the vector of names to do this... My attempt to do this is in the SearchContactsByFirstLetter function...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <time.h>
#define MAX_LENGTH 50
typedef struct
{
char name[MAX_LENGTH];
char number[MAX_LENGTH];
int bd;
int bdm;
} ContactBook;
void ListContacts(ContactBook **c, int quant)
{
int i;
printf("\n List of contacts: \n");
printf("\t---------------------\n");
for (i = 0; i < quant; i++)
{
printf("\t%d = birthday: %2d month %2d\t name: %s \t number: %s\n", i + 1, c[i]->bd, c[i]->bdm, c[i]->name, c[i]->number);
}
}
int addContacts(ContactBook **c, int quant, int size)
{
if (quant < size)
{
ContactBook *new = malloc(sizeof(ContactBook));
printf("\nenter contact name: ");
scanf("%49[^\n]", new->name);
printf("\nenter number: ");
scanf("%s", new->number);
printf("\nenter the birthday ");
scanf("%d", &new->bd);
printf("\n enter the month birthday: ");
scanf("%d", &new->bdm);
c[quant] = new;
return 1;
}
else
{
printf("\n full list.\n");
return 0;
}
}
int deleteContact(ContactBook **c, int quant)
{
int id;
ListContacts(c, quant);
printf("\n\t Enter the id you want to delete: \n");
scanf("%d", &id);
id--;
if (id >= 0 && id < quant)
{
free(c[id]);
if (id < quant - 1)
{
c[id] = c[quant - 1];
}
return -1;
}
else
{
printf("\n\t wrong code;\n");
return 0;
}
}
void birthdays(ContactBook **c, int quant)
{
int i;
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf(" os aniversariantes do mês são: \n");
for (i = 0; i < quant; i++)
{
if (tm.tm_mon + 1 == c[i]->bdm)
{
printf("\t%d = birthday: %2d month %2d\t name: %s \t number: %s\n", i + 1, c[i]->bd, c[i]->bdm, c[i]->name, c[i]->number);
}
}
}
void SearchContactByFirstLetter(ContactBook **c, int quant)
{
int i;
char searchedName[2];
printf("\n Search a letter: \n");
scanf("%s", searchedName);
getchar();
for (i = 0; i < quant; i++)
{
if (strcmp(searchedName, c[i]->name[0]) == 0)
{
printf("\t\nname: %s, \nnumber: %s, \nbirthday: %d \nmonth birthday %d \t\n", c[i]->name, c[i]->number, c[i]->bd, c[i]->bdm);
}
}
}
void SearchContact(ContactBook **c, int quant)
{
int i;
char searchedName[30];
printf("\n Search name: \n");
scanf("%s", searchedName);
getchar();
for (i = 0; i < quant; i++)
{
if (strcmp(searchedName, c[i]->name) == 0)
{
printf("\t\nname: %s, \nnumber: %s, \nbirthday: %d \nmonth birthday %d \t\n", c[i]->name, c[i]->number, c[i]->bd, c[i]->bdm);
}
}
}
void saveBinary(char arquivo[], ContactBook **c, int quant)
{
FILE *file = fopen(arquivo, "wb");
int i;
if (file)
{
for (i = 0; i < quant; i++)
fwrite(c[i], sizeof(ContactBook), 1, file);
fclose(file);
}
else
printf("erro");
}
int readBinaryArq(char arquivo[], ContactBook **c)
{
int quant = 0;
ContactBook *new = malloc(sizeof(ContactBook));
FILE *file = fopen(arquivo, "rb");
if (file)
{
while (fread(new, sizeof(ContactBook), 1, file))
{
c[quant] = new;
quant++;
new = malloc(sizeof(ContactBook));
}
fclose(file);
}
else
printf("\nerro");
return quant;
}
int main()
{
ContactBook *contacts[50];
int option, size = 50, quant = 0;
char arq2[] = ("agenda.dat");
quant = readBinaryArq(arq2, contacts);
do
{
printf(" \n\t0 - exit\n\t1 - register contact\n\t2 - Remove contact\n\t3- List contacts\n\t4- Search contact\n\t5 - ver aniversariantes do mês\n\t6-Pesquisar por inicial\n ");
scanf("%d", &option);
getchar();
switch (option)
{
case 1:
quant += addContacts(contacts, quant, size);
break;
case 2:
quant += deleteContact(contacts, quant);
break;
case 3:
ListContacts(contacts, quant);
break;
case 4:
SearchContact(contacts, quant);
break;
case 5:
birthdays(contacts, quant);
break;
}
saveBinary(arq2, contacts, quant);
} while (option != 0);
return 0;
}
if (strcmp(searchedName, c[i]->name[0]) == 0)
That should be:
if (searchedName[0] == c[i]->name[0])
But you probably shouldn't read in a string in the first place if you only want to read a single character.

Search function in CRUD with C

I'm making a contact book in C and I've already done the parts of registering contact, listing all contacts and deleting a contact, but I need to elaborate the part of searching the contact, and also searching contacts that start with a given string, but I'm not succeeding... I'll leave my code below to see if anyone can help me identify where I'm going wrong:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 50
typedef struct
{
char name[MAX_LENGTH];
char number[MAX_LENGTH];
int bd;
char bdm[MAX_LENGTH];
} ContactBook;
void ListContacts(ContactBook **c, int quant)
{
int i;
printf("\n List of contacts: \n");
for (i = 0; i < quant; i++)
{
printf("\t%d = birthday: %2d month %s\t name: %s \t number: %s\n", i + 1, c[i]->bd, c[i]->bdm, c[i]->name, c[i]->number);
}
}
int addContacts(ContactBook **c, int quant, int size)
{
if (quant < size)
{
ContactBook *new = malloc(sizeof(ContactBook));
printf("\nenter contact name: ");
scanf("%s", new->name);
printf("\nenter number: ");
scanf("%s", new->number);
printf("\nenter the birthday ");
scanf("%d", &new->bd);
printf("\n enter the month birthday: ");
scanf("%s", new->bdm);
c[quant] = new;
return 1;
}
else
{
printf("\n full list.\n");
return 0;
}
}
int deleteContact(ContactBook **c, int quant)
{
int id;
ListContacts(c, quant);
printf("\n\t Enter the id you want to delete: \n");
scanf("%d", &id);
getchar();
id--;
if (id >= 0 && id < quant)
{
free(c[id]);
if (id < quant - 1)
{
c[id] = c[quant - 1];
}
return -1;
}
else
{
printf("\n\t wrong code;\n");
return 0;
}
}
void SearchContact(ContactBook **c, int quant)
{
int i;
char searchedName[30];
for (i = 0; i < quant; i++)
{
printf("\n Search name: \n");
scanf("%s", searchedName);
getchar();
if (strcmp(searchedName, c[i]->name) == 0)
{
printf("the name: %s was found", c[i]->name);
}
else
{
printf("name not found");
}
}
}
int main()
{
ContactBook *contacts[50];
int option, size = 50, quant = 0;
do
{
printf(" \n\t0 - exit\n\t1 - register contact\n\t2 - Remove contact\n\t3- List contacts\n\t4- Search contact\n\t");
scanf("%d", &option);
getchar();
switch (option)
{
case 1:
quant += addContacts(contacts, quant, size);
break;
case 2:
quant += deleteContact(contacts, quant);
break;
case 3:
ListContacts(contacts, quant);
break;
case 4:
SearchContact(contacts, quant);
break;
}
} while (option != 0);
return 0;
}

Student information using queue

Can you tell me if this is correct way to do?
This is my sample code in student information in queue. my problem is that I want to insert a student number in the struct but it doesn't repeat when I input the same student number.
#include <stdio.h>
#include <stdlib.h>
struct node
{
char No[12],Name[24],crsysr[10];
float gwa;
struct node *ptr;
}*front,*rear,*temp,*front1;
int frontelement();
void insert(char *data, char *name,char *yearsec,float gwa);
void del();
void empty();
void display();
void create();
void queuesize();
void removeduplicate();
int count = 0;
void main()
{
int ch, pos,i,e;
char no[12], name[24],crsyr[10];
float gwa,tgwa;
create();
while (1)
{
printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Queue size");
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf ("how Many student do you want to enter?: ");
int n;
scanf("%d",&n);
for(int i=0; i<n; ++i)
{
fflush(stdin);
printf("\n Enter Student number : ");
gets(no);
printf("\n Enter Student name : ");
gets(name);
printf("\n Enter Student Year and Sec : ");
gets(crsyr);
fflush(stdin);
printf("\n Enter Student gwa : ");
scanf("%f", &gwa);
insert(no, name, crsyr, gwa);
count++;
}
printf("Press any key to contiue...");
getch();
system("cls");
break;
case 2:
del();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
system("cls");
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
system("cls");
removeduplicate(temp->ptr);
display();
printf("Press any key to contiue...");
getch();
system("cls");
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}
void create()
{
front = rear = NULL;
}
void queuesize()
{
printf("\n Queue size : %d", count);
}
void insert(char *data, char *name,char *yearsec, float gwa)
{
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
strcpy(rear->No, data);
strcpy(rear->Name, name);
strcpy(rear->crsysr, yearsec);
rear->gwa=gwa;
front = rear;
}
else
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
strcpy(temp->No, data);
strcpy(temp->Name, name);
strcpy(temp->crsysr, yearsec);
temp->gwa=gwa;
temp->ptr = NULL;
rear = temp;
}
}
void display()
{
front1 = front;
int i;
if ((front1 == NULL) && (rear == NULL))
{
printf("Queue is empty");
return;
}
printf("Student Number\t\tName\t\tSection\t\tGwa\n\n");
while (front1 != rear)
{
printf("%s \t",front1->No);
printf("%s \t",front1->Name);
printf("%s \t",front1->crsysr);
printf("%f \t", front1->gwa);
front1 = front1->ptr;
printf("\n");
}
if (front1 == rear)
printf("%s \t",front1->No);
printf("%s \t",front1->Name);
printf("%s \t",front1->crsysr);
printf("%f\t", front1->gwa);
printf("\n");
}
void del()
{
front1 = front;
if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequed Student num : " );
puts(front->No);
printf("\n Dequed Name : ");
puts(front->Name);
printf("\n Dequed Year and section : ");
puts(front->crsysr);
printf("\n Dequed GWA : %f", front->gwa);
free(front);
front = front1;
}
else
{
printf("\n Dequed Student Num : ", front->No);
printf("\n Dequed Name : ", front->Name);
printf("\n Dequed Year and section :", front->crsysr);
printf("\n Dequed GWA : %f", front->gwa);
free(front);
front = NULL;
rear = NULL;
}
count--;
}
int frontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->No,front->Name,front->crsysr,front->gwa);
else
return 0;
}
void empty()
{
if ((front == NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}
void removeduplicate(struct node *front) {
struct node *ptr1, *ptr2, *duplicate;
ptr1 = front;
while (ptr1 != NULL && ptr1->ptr != NULL)
{
ptr2 = ptr1;
/* Compare the current element with rest of the elements */
while (ptr2->ptr != NULL)
{
if (strcmp(ptr1->No == ptr2->ptr->No && ptr1->Name == ptr2->ptr->Name && ptr1->crsysr == ptr2->ptr->crsysr && ptr1->gwa == ptr2->ptr->gwa)==0)
{
duplicate = ptr2->ptr;
ptr2->ptr = ptr2->ptr->ptr;
free(duplicate);
} else
{
ptr2 = ptr2->ptr;
}
ptr1 = ptr1->ptr;
}
}
}

assignment to expression with array type error in c

I am getting this error as shown in the image pls tell me how to fix it.
the error is in line 115 of the code
#include<stdio.h>
#include<string.h>
#define MAX 100
#define product_limit 50
typedef struct {
int p_id;
char p_name[product_limit + 1];
int p_quantity;
int unit_price;
char type_product[50];
} product;
int main()
{
int ok = 1, menu;
do
{
menu = display_menu();
if(menu < 1 || menu > 7)
{
printf("Invaid option.\n");
}
else
{
switch(menu)
{
case 1:
add_product();
break;
case 2:
change_product();
break;
case 3:
display_all_products();
break;
}
}
}
while(ok);
printf("Exiting Program.\n");
return 0;
}
int display_menu()
{
int menu;
printf("Choose option from below.\n");
printf("1. Add new product.\n");
printf("2. Update product.\n");
printf("3. Display products.\n");
printf(". Exit.\n");
scanf("%d", &menu);
return menu;
}
product products[MAX];
int c_p = 0;
int product_exists(int id)
{
int x;
for(x=0;x<c_p;x++)
{
if(products[x].p_id == id)
{
return x;
}
}
return -1;
}
int add_product()
{
int price,id,quantity,type;
char name[product_limit + 1];
printf("Product ID: ");
scanf("%d", &id);
if(product_exists(id) != -1)
{
printf("ID: %d already exists.\n", id);
return;
}
printf("Enter Product Name: ");
scanf("%s", name);
printf("Enter Quantity: ");
scanf("%d", &quantity);
printf("Enter Price: ");
scanf("%d", &price);
printf("Enter Product Type:");
scanf("%s",type);
products[c_p].p_id = id;
strcpy(products[c_p].p_name, name);
products[c_p].p_quantity = quantity;
products[c_p].unit_price = price;
c_p++;
printf("Product added Successfully\n");
}
int change_product()
{
int id, exists,name;
char z[2];
printf("Product ID: ");
scanf("%d", &id);
exists = change_product(id);
if(exists == -1) {
printf("ID: %d not exists.\n", id);
printf("Type Y to try once more or N back to menu: ");
scanf("%s", z);
if(strcmp(z, "Y") == 0)
{
change_product();
}
} else {
printf("Product found successfully\n");
printf("Product Name: %s\n", products[exists].p_name);
printf("Type new name: ");
scanf("%d", name);
products[exists].p_name += name;
printf("Successfully updated.\n");
}
}
int display_products()
{
int x;
if(c_p == 0)
{
printf("No products were added\n");
return;
}
printf("Products\n\n");
for(x = 0; x < c_p; x++)
{
printf("Product ID: %d\n", products[x].p_id);
printf("Product Name: %s\n", products[x].p_name);
printf("Quantity: %d\n", products[x].p_quantity);
printf("Product price: %d\n", products[x].unit_price);
printf("Product type:%s\n",products[x].p_name);
printf("\n");
}
}
You're trying to add an integer to a string. This is not allowed in C:
products[exists].p_name += name;
Looking at the change_product method it seems like maybe you want to update the name field or concatenate it. I think you should do these things:
Read all compiler warnings and consider addressing them, They are addressing valid concerns like not declaring your functions first, not returning any int value in add_product, display_product etc which is supposed to return int. Provide a function body for display_all_products (Did you mean display_products()?)
Use a string variable for updating name char newName[product_limit + 1] and use library functions from C string library to either concatenate(strcat) or copy(strcpy) newName taken as user input to products[exists].p_name:
char newName[product_limit + 1];
// ...
} else {
printf("Type new name: ");
fgets(newName, product_limit + 1, stdin);
strcpy(products[exists].p_name, newName);
}
}
You can't add integer to string.
You have used string functions like strcpy() and should do the same for this.
You have also made other errors :
declaring int for string(char array)
wrong return data type
calling wrong funtion
I have fixed those errors, do side by side comparison.
#include<stdio.h>
#include<stdlib.h>//here
#include<string.h>
#define MAX 100
#define product_limit 50
//here
void add_product(void);
void change_product(void);
int display_menu(void);
void display_products(void);
int product_exists(int);
typedef struct {
int p_id;
char p_name[product_limit + 1];
int p_quantity;
int unit_price;
char type_product[50];
} product;
int main()
{
int ok = 1, menu;
do
{
menu = display_menu();
if(menu < 1 || menu > 4)
{
printf("Invaid option.\n");
}
else
{
switch(menu)
{
case 1:
add_product();
break;
case 2:
change_product();
break;
case 3:
display_products();//here
break;
case 4:
exit(0);//here
}
}
}
while(ok);
printf("Exiting Program.\n");
return 0;
}
int display_menu()
{
int menu;
printf("Choose option from below.\n");
printf("1. Add new product.\n");
printf("2. Update product.\n");
printf("3. Display products.\n");
printf("4. Exit.\n");
scanf("%d", &menu);
return menu;
}
product products[MAX];
int c_p = 0;
int product_exists(int id)
{
int x;
for(x=0;x<c_p;x++)
{
if(products[x].p_id == id)
{
return x;
}
}
return -1;
}
void add_product() // here
{
int price,id,quantity;
char type[product_limit + 1];
char name[product_limit + 1];//here
printf("Product ID: ");
scanf("%d", &id);
if(product_exists(id) != -1)
{
printf("ID: %d already exists.\n", id);
return;
}
printf("Enter Product Name: ");
scanf("%s", name);
printf("Enter Quantity: ");
scanf("%d", &quantity);
printf("Enter Price: ");
scanf("%d", &price);
printf("Enter Product Type:");
scanf("%s",type);
products[c_p].p_id = id;
strcpy(products[c_p].p_name, name);
products[c_p].p_quantity = quantity;
products[c_p].unit_price = price;
strcpy(products[c_p].type_product,type);//here
c_p++;
printf("Product added Successfully\n");
}
void change_product() //here
{
int id, exists;
char z[2];
char name[product_limit + 1];//here
printf("Product ID: ");
scanf("%d", &id);
exists = product_exists(id);//here
if(exists == -1)
{
printf("ID: %d not exists.\n", id);
printf("Type Y to try once more or N back to menu: ");
scanf("%s", z);
if(strcmp(z, "Y") == 0)
{
change_product();
}
}
else
{
printf("Product found successfully\n");
printf("Product Name: %s\n", products[exists].p_name);
printf("Type new name: ");
scanf("%s", &name);//here
strcpy(products[exists].p_name, name);//here
printf("Successfully updated.\n");
}
}
void display_products() //here
{
int x;
if(c_p == 0)
{
printf("No products were added\n");
return;
}
printf("Products\n\n");
for(x = 0; x < c_p; x++)
{
printf("Product ID: %d\n", products[x].p_id);
printf("Product Name: %s\n", products[x].p_name);
printf("Quantity: %d\n", products[x].p_quantity);
printf("Product price: %d\n", products[x].unit_price);
printf("Product type:%s\n",products[x].type_product);//here
printf("\n");
}
}

Remove element from struct type

I'm trying to create this function to remove an element of the user's choosing from a pointer struct array type.
Here is my function. I keep getting this error when my code hits this function.
error: incompatible types when assigning to type ‘char[1000]’ from type ‘char *’
PhoneBook[iRecord - 1].cFirstName = PhoneBook[x].cFirstName;
void delete_record(pb *PhoneBook)
{
int x;
int iRecord = 0;
print(PhoneBook);
printf("\nEnter number of record you want to delete: ");
scanf("%d", &iRecord);
printf("\nRecord to be deleted: %d. %s\n", iRecord - 1, PhoneBook[iRecord - 1].cFirstName);
for (x = strlen(PhoneBook[iRecord - 1].cFirstName); x <= strlen(PhoneBook[iRecord - 1].cFirstName); x--) {
PhoneBook[iRecord - 1].cFirstName = PhoneBook[x].cFirstName;
}
printf("\nModified record: %s\n\n",PhoneBook[iRecord - 1].cFirstName);
}
Here's the full code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct phonebook {
char cFirstName[1000];
char cLastName[1000];
char cNumber[1000];
} pb;
int entry(pb *);
void modify(pb *);
void delete_record(pb *);
void print(pb *);
void convert_u(char *);
//global variable
int MAX_NAME_ENTRY = 0;
int main()
{
int iResponse = 0;
pb *PhoneBook = (pb *) calloc(0, sizeof(pb));
if (PhoneBook == NULL) {
printf("\nMemory allocation failed.\n\n");
return 1;
}
do {
printf("\nPhonebook Menu\n****************\n\n");
printf("1. Enter new contact\n2. Modify existing contact\n3. Delete contact\n4. Print Phonebook \n5. Exit\n\n");
printf("Please make selection: ");
scanf("%d", &iResponse);
if (iResponse == 1) {
entry(PhoneBook);
}
else if (iResponse == 2) {
modify(PhoneBook);
}
else if (iResponse == 3) {
delete_record(PhoneBook);
//printf("\nWorking on it...\n");
}
else if (iResponse == 4) {
print(PhoneBook);
}
} while (iResponse != 5);
free(PhoneBook);
return 0;
}
int entry(pb *PhoneBook)
{
int x;
char yes_no[] = "YES";
pb *newPhoneBook = realloc(PhoneBook, (10 * sizeof(pb)));
if (newPhoneBook == NULL) {
printf("\nOut of memory!\n\n");
return 1;
}
else {
PhoneBook = newPhoneBook;
}
if (MAX_NAME_ENTRY == 10) {
printf("\nMax Number of names entered.\n");
}
for (x = MAX_NAME_ENTRY; x < 10; x++) {
if (MAX_NAME_ENTRY == 9) {
printf("\nLast entry.\n");
}
if (x > 0) {
system("clear");
printf("\nAnother entry(yes/no)? ");
scanf("%s", yes_no);
convert_u(yes_no);
}
if (strcmp(yes_no, "YES") == 0) {
printf("\nFirst Name: ");
scanf("%s", PhoneBook[x].cFirstName);
printf("\nLast Name: ");
scanf("%s", PhoneBook[x].cLastName);
printf("\nPhone Number: ");
scanf("%s", PhoneBook[x].cNumber);
MAX_NAME_ENTRY++;
}
else if (strcmp(yes_no, "NO") == 0) {
break;
}
}
}
void modify(pb *PhoneBook)
{
int iModify = 0;
char name_num[6] = {'\0'};
print(PhoneBook);
printf("\nWhich entry would you like to modify? ");
scanf("%d", &iModify);
printf("\nModify name or number? ");
scanf("%s", name_num);
convert_u(name_num);
if (strcmp(name_num, "NAME") == 0) {
printf("\nEnter new name: ");
scanf("%s %s", PhoneBook[iModify - 1].cFirstName, PhoneBook[iModify - 1].cLastName);
}
else if (strcmp(name_num, "NUMBER") == 0) {
printf("\nEnter new number: ");
scanf("%s", PhoneBook[iModify - 1].cNumber);
}
}
void delete_record(pb *PhoneBook)
{
int x;
int iRecord = 0;
print(PhoneBook);
printf("\nEnter number of record you want to delete: ");
scanf("%d", &iRecord);
printf("\nRecord to be deleted: %d. %s\n", iRecord - 1, PhoneBook[iRecord - 1].cFirstName);
for (x = strlen(PhoneBook[iRecord - 1].cFirstName); x <= strlen(PhoneBook[iRecord - 1].cFirstName); x--) {
PhoneBook[iRecord - 1].cFirstName = PhoneBook[x].cFirstName;
}
printf("\nModified record: %s\n\n",PhoneBook[iRecord - 1].cFirstName);
}
void print(pb *PhoneBook)
{
int x;
for (x = 0; x < 10; x++) {
if (strlen(PhoneBook[x].cFirstName) == 0 && strlen(PhoneBook[x].cLastName) == 0) {
break;
}
printf("\n%d. Name: %s %s", x + 1, PhoneBook[x].cFirstName, PhoneBook[x].cLastName);
printf("\n Number: %s\n\n", PhoneBook[x].cNumber);
}
}
void convert_u(char *string)
{
int x;
for (x = 0; x < strlen(string); x++) {
string[x] = toupper(string[x]);
}
}
Any suggestions on what I'm doing wrong?
An array name is not a modifiable lvalue. Hence, arrays are not assignable in C.
Quoting C11, chapter §6.5.16
An assignment operator shall have a modifiable lvalue as its left operand.
and regarding the modifiable lvalue, chapter §6.3.2.1
A modifiable lvalue is an lvalue that
does not have array type, [...]
You need to use strcpy() instead to copy the content.
it will not work strcpy, you have to copy the whole record over the other. then realloc the phonebook to new size.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct phonebook {
char cFirstName[50];
char cLastName[50];
char cNumber[50];
} pb;
int entry();
void modify();
void delete_record();
void print_record(int rec);
void print();
void convert_u(char *);
//global variables
int MAX_NAME_ENTRY = 0;
pb *PhoneBook = NULL;
#define YES "YES"
#define NO "NO"
const char *menu=
" Phonebook Menu \n"
" **************** \n"
" \n"
" 1. Enter new contact \n"
" 2. Modify existing contact \n"
" 3. Delete contact \n"
" 4. Print Phonebook \n"
" 5. Exit \n"
" \n"
" Please make selection: ";
int main(void){
int iResponse = 0;
do {
printf("%s",menu);
scanf("%d", &iResponse);
switch (iResponse) {
case 1:
entry();
break;
case 2:
modify();
break;
case 3:
delete_record();
break;
case 4:
print();
}
} while (iResponse != 5);
free(PhoneBook);
return 0;
}
int str_input(const char *text, char *buff){
printf("%s" , text);
scanf("%s" , buff);
}
int entry(void)
{
int x;
char yes_no[] = YES;
pb *newPhoneBook;
if (MAX_NAME_ENTRY == 10) {
printf("\nMax Number of names entered.\n");
return 0;
}
while(1) {
newPhoneBook = realloc(PhoneBook,(MAX_NAME_ENTRY +1) * sizeof(pb)) ;
if (!newPhoneBook) {
perror("entry::realloc()");
return 1;
}
PhoneBook = newPhoneBook;
if (MAX_NAME_ENTRY == 9) {
printf("\n *** This is the Last entry. *** \n");
}
printf("RECORD: %d\n",MAX_NAME_ENTRY+1);
str_input("\nFirst Name: " , PhoneBook[MAX_NAME_ENTRY].cFirstName);
str_input("\nLast Name: " , PhoneBook[MAX_NAME_ENTRY].cLastName);
str_input("\nPhone Number: " , PhoneBook[MAX_NAME_ENTRY].cNumber);
MAX_NAME_ENTRY++;
if(MAX_NAME_ENTRY == 10)
break;
printf("\nAnother entry(yes/no)? ");
scanf("%s", yes_no);
convert_u(yes_no);
if (strcmp(yes_no, YES))
break;
system("clear");
}
}
int checkRecordExists(int iRecord){
if(iRecord<1 || iRecord>MAX_NAME_ENTRY){
printf("Record %d do not exists\n",iRecord);
return 0;
}
return 1;
}
void modify(void){
int iModify = 0;
char name_num[6] = {'\0'};
printf("\nWhich entry would you like to modify? ");
scanf("%d", &iModify);
if(!checkRecordExists(iModify))
return;
iModify --;
print_record(iModify);
str_input("\nModify name or number? ", name_num);
convert_u(name_num);
if (strcmp(name_num, "NAME") == 0) {
str_input("\nFirst Name: " , PhoneBook[iModify].cFirstName);
str_input("\nLast Name: " , PhoneBook[iModify].cLastName);
}
else if (strcmp(name_num, "NUMBER") == 0) {
str_input("\nPhone Number: " , PhoneBook[iModify].cNumber);;
}
}
void delete_record(void)
{
int x;
int iRecord = 0;
printf("\nEnter number of record you want to delete: ");
scanf("%d", &iRecord);
if(!checkRecordExists(iRecord))
return;
iRecord--;
MAX_NAME_ENTRY--;
for( x=iRecord;x<MAX_NAME_ENTRY;x++)
memcpy(&PhoneBook[x],&PhoneBook[x+1],sizeof(pb));
PhoneBook = realloc(PhoneBook,(MAX_NAME_ENTRY + 1) * sizeof(*PhoneBook) );
}
void print_record(int rec){
printf("\n"
"%02d. Name: %s %s\n"
" Number: %s\n"
"\n",
rec + 1, PhoneBook[rec].cFirstName, PhoneBook[rec].cLastName, PhoneBook[rec].cNumber);
}
}
void print(void){
int x;
for (x = 0 ; x < MAX_NAME_ENTRY ; x++) {
print_record(x);
}
}
void convert_u(char *string){
while(*string){
*string = toupper(*string);
string ++;
}
}

Resources