I'm having difficulty writing a loop that will ask a user if he/she wants to continue the purchase of the products. It's part of my coursework at school. I have written all the required functions but Im struggling to get the loop to work.
Basically, what I want the loop to do is ask a user if he/she wants to continue the purchase and the answer should be either Y or N. Which will then take the remaining budget, implement it back to the program and run it again with that budget in mind, then deduct the value of the product chosen.
I have been trying to write that loop for more than 2 hours now and I'm running out of ideas.
That's the code I'm working with:
#include <stdio.h>
int getItemPrice(char itemPrefix, int applePrice, int orangePrice, int pearPrice);
displayMenu(int applePrice, int orangePrice, int pearPrice);
withinBudget(int budget, char purchase, int applePrice, int orangePrice, int pearPrice);
purchaseItem(int budget, char purchase, int applePrice, int orangePrice, int pearPrice);
int main()
{
int orangePrice, applePrice, pearPrice, budget;
char purchase;
printf("*****************\n");
printf("Item prefixes\n");
printf("A: Apple\n");
printf("O: Orange\n");
printf("P: Pear\n");
printf("*****************\n\n");
printf("***************\n");
printf("*** MyStore ***\n");
printf("***************\n\n");
printf("**** SHOPKEEPER PANEL ****\n");
printf("Welcome to the store. Please enter the prices for the following products: \n");
printf("Please enter the price for the Orange: \x9C");
scanf_s("%d", &orangePrice);
printf("Please enter the price for the Apple: \x9C");
scanf_s("%d", &applePrice);
printf("Please enter the price for the Pear: \x9C");
scanf_s("%d", &pearPrice);
printf("\n\n");
displayMenu(applePrice, orangePrice, pearPrice);
printf("**** Customer menu ****\n");
printf("Please enter your budget: \x9C");
scanf_s("%d", &budget);
printf("Please enter the item you would like to purchase using the item Prefix: ");
scanf_s(" %c", &purchase, 1);
printf("\n\n");
displayMenu(applePrice, orangePrice, pearPrice);
withinBudget(budget, purchase, applePrice, orangePrice, pearPrice);
purchaseItem(budget, purchase, applePrice, orangePrice, pearPrice);
return 0;
};
int getItemPrice(char itemPrefix, int applePrice, int orangePrice, int pearPrice)
{
if (itemPrefix == 'A') {
return applePrice;
}
else if (itemPrefix == 'O') {
return orangePrice;
}
else if (itemPrefix == 'P') {
return pearPrice;
}
else {
return -1;
}
return getItemPrice;
}
displayMenu(int applePrice, int orangePrice, int pearPrice)
{
printf("**** Shop Menu ****\n");
printf("Item:\t\tPrice\n");
printf("A:\t\t\x9C%d\n", applePrice);
printf("O:\t\t\x9C%d\n", orangePrice);
printf("P:\t\t\x9C%d\n", pearPrice);
printf("\n\n");
return 0;
}
withinBudget(int budget, char purchase, int applePrice, int orangePrice, int pearPrice)
{
int getItemPrice(itemPrefix, applePrice, orangePrice, pearPrice);
if (purchase == 'A') {
return applePrice;
}
else if (purchase == 'O') {
return orangePrice;
}
else if (purchase == 'P') {
return pearPrice;
}
else {
return -1;
}
}
purchaseItem(int budget, char purchase, int applePrice, int orangePrice, int pearPrice)
{
int items ;
int calculation;
if (purchase == 'A') {
items = applePrice;
}
else if (purchase == 'O') {
items = orangePrice;
}
else if (purchase == 'P') {
items = pearPrice;
}
else {
items = -1;
}
if (items != -1) {
calculation = budget - items;
if (calculation >= 0) {
printf("Purchase was a success!\n");
printf("Purchase details\n");
printf("----------------------\n");
printf("Item: %c\n", purchase);
printf("Price: \x9C%d\n", items);
printf("Remaining budget: \x9C%d\n\n", calculation);
printf("Thanks for shopping with us!");
}
else {
items = -1;
}
}
if (items == -1) {
printf("Purchase FAILED!\n");
printf("Low budget or invalid item!\n\n");
printf("Thanks for shopping with us!");
}
;
I have already tried writing the while loop in the body of the program as well as inside of the purchase item function. I'm completely clueless at this point and don't really know what can I do to make it work. Or what I'm not doing that would help me this program to work as I want it to.
Any help would be appreciated. As well as any tips on what can I do to improve it.
You can implement a loop logic like this:
int main(void){
... // Your definitons
bool proceed = true;
while(proceed){
... // All your code here
bool isValid = false; // Check the answer character's validity
while(!isValid){
printf("Would you like to purchase anything else? [Y / N]");
char answer = getchar();
putchar('\n'); // Add a line feed
if (answer == 'Y' || answer == 'y'){
proceed = true;
isValid = true;
}
else if (answer == 'N' || answer == 'n'){
proceed = false;
isValid = true;
}
else{
// Entered an unexpected character, force the user to enter a valid character
printf("Please enter a valid answer\n");
isValid = false;
}
}
}
return 0;
}
Related
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;
}
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");
}
}
This program must handle data that represents the products used in the factory. It is desired that the product represents the following characteristics: Code, description unit of measure, and price; In turn, if the product is imported you want to know the origin of the product, while if it is purchased in the square you want to know the name of the provider's phone number.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <stdbool.h>
#include <winsock.h>
void clrscr();
typedef enum {IMPORTED, LOCAL} type;
typedef struct
{
int code;
char description [20];
char MeasureUnit [5];
float price;
type discriminant;
union
{
char origin [20];
char destination [20];
int telephone;
} impoExpo;
} Product;
//this procedure fails
void loadProduct (Product *p)
{
printf("\nEnter the code:");
scanf("%d",&Product.code); //<-error: expected expression before 'Product'
fflush(stdin);
printf("\nEnter the description:");
scanf("%s",Product.description);
printf("Indicate the unit of measure:");
scanf("%s",Product.MeasureUnit);
printf("Enter the price:");
scanf("%f",&Product.price);
int i;
printf("\nInsert 1 if imported");
scanf("%d", &i);
if(i == 1)
{
p->discriminant = IMPORTED;
}
else
{
p->discriminant = LOCAL;
}
if(p->discriminant == IMPORTED)
{
printf("\nEnter source: ");
gets(p->impoExpo.origin);
}
else
{
printf("\nEnter the phone");
scanf("%d", &p->impoExpo.telephone);
}
}
//it is also
void showProduct (Product p)
{
printf("\nCode: %d", p.code); //<----- error: request for member 'code' in something not a structure or union
printf("\nDescription");
printf("%s", p.description);
printf("\nMeasurement unit:");
printf("%s", p.MeasureUnit);
printf("\nPrice:% .2f", p.price);
printf("\nType:");
if (p.discriminant == IMPORTED)
{
printf("Imported:");
printf("\nOrigin: %s", p.impoExpo.origin);
printf("%s", p.impoExpo.origin);
}
else
{
printf("Local:");
printf("\nTelephone: %d", p.impoExpo.telephone);
}
}
//this one also
bool areequal (Product p1, Product p2)
{
bool equal = false;
if ((p1.code == p2.code) && (p1.description == p2.description))
{
if ((p1.MeasureUnit == p2.MeasureUnit) && (p1.price == p2.price))
{
if (p1.discriminant == p2.discriminant)
{
if (p1.discriminant == IMPORTED)
{
if (p1.impoExpo.origin == p2.impoExpo.origin)
{
equal = true;
}
}
else
{
if (p1.impoExpo.telephone == p2.impoExpo.telephone)
{
equal = true;
}
}
}
}
}
return equal;
}
//this funciĆ³n ok
void copy (Product * const destination, const Product * const origin)
{
destination->code = origin->code;
(*destination->description) = (*origin->description);
(*destination->MeasureUnit) = (*origin->MeasureUnit);
destination->price = origin->price;
destination->discriminant = origin->discriminant;
if(destination->discriminant == IMPORTED)
(*destination->impoExpo.origin) = (*origin->impoExpo.origin);
else
destination->impoExpo.telephone = origin->impoExpo.telephone;
}
//and the latter also
int main ()
{
int option;
do
{
clrscr();
printf("Welcome to the program\n");
printf("Enter an option\n");
printf("1. Load a product\n");
printf("2. Show product\n");
printf("3. Check if two products are the same\n");
printf("0. Exit");
printf("Enter the option, and press ENTER");
scanf("%d",&option);
switch (option)
{
case 1:
loadProduct(&p);
getch();
break;
case 2:
showProduct(p);
getch();
break;
case 3:
printf("Enter the name of the product 1");
scanf("%d",&p1);
printf("Enter the name of the product 2");
scanf("%d",&p2);
printf("% d",areequal (p1, p2));
getch();
break;
}
} while (option != 0);
getch();
return 0;
}
void clrscr()
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coord = {0, 0};
DWORD count;
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hStdOut, &csbi);
FillConsoleOutputCharacter(hStdOut, ' ', csbi.dwSize.X * csbi.dwSize.Y, coord, &count);
SetConsoleCursorPosition(hStdOut, coord);
}
Product is a pointer, so you have to access its members using the arrow notation:
scanf("%d",&p->code); //<-error: expected expression before 'Product'
I could not find specific student_Id info from a rage of given info.suppose, I am taking input from 1 to 100 all student info. now I want to find only 50th number student_ID all info.i could not do it. how it possible.here show my code. what's wrong with my code and how fixed it.thanks
# include <string.h>
# include <stdio.h>
# include <stdlib.h>
# include <conio.h>
struct student
{
char student_id[100];
char name[10];
int m[50],credit[100],sub[100];
int total,sumCredit;
float GP[100];
char result[5];
char grade[100][10];
double sumCreditxGP;
}*p,*s;
float gradesToGP(float marks);
char *markToG(float gp);
void lines(void);
void main()
{
int i,j,l,n,sub,k;
// clrscr();
printf("Enter the no. of students : ");
scanf("%d",&n);
p=(struct student*) malloc(n*sizeof(struct student));
//printf("%d",p);
//exit(0);
s=p;
for(i=0; i<n; i++)
{
printf("Enter a student id : ");
scanf("%s",&p->student_id);
printf("Enter a name : ");
scanf("%s",&p->name);
printf("Enter the no. of subject : ");
scanf("%d",&p->sub[i]);
p-> total=0;
p-> sumCredit=0;
p-> sumCreditxGP=0;
l=0;
for(j=0; j<p->sub[i]; j++)
{
one:
printf("Enter Marks of %d Subject\t%d : ",j+1,p->sub[i]);
scanf("%d",&p->m[j]);
printf("Enter Credit Hour: ");
scanf("%d",&p->credit[j]);
p->GP[j] = gradesToGP((float)p->m[j]);
strcpy(p->grade[j],markToG(p->m[j]));
if((p->m[j])>100)
{
printf("---------------Wrong Value Entered-----------\n");
goto one;
}
p->total+=p->m[j];
p->sumCredit+=p->credit[j];
p->sumCreditxGP+=p->credit[j]*p->GP[j];
if(p->m[j]<40)
l=1;
}
if(l==0)
strcpy(p->result,"PASS");
else
strcpy(p->result,"FAIL");
p++;
}
char search_id[10];
printf("Enter id to find specific student ");
scanf("%s",search_id);
//PROBLEM START HERE
for(i=0; i<n; i++)
{
if(p->student_id==search_id){
printf("found");
printf("%s",s->student_id);
}else{
printf("Not found");
}
s++;
}
getch();
}
float gradesToGP(float marks)
{
if (marks>=80 && marks<=100)
{
return(float)4.00;
}
else if (marks>=75 && marks<=79)
{
return(float)3.67;
}
else if (marks>=70 && marks<=74)
{
return(float)3.33;
}
else if (marks>=65 && marks<=69)
{
return(float)3.00;
}
else if (marks>=60 && marks<=64)
{
return(float)2.67;
}
else if (marks>=55 && marks<=59)
{
return(float)2.33;
}
else
{
return(float)5.00;
}
}
char *markToG(float marks)
{
if (marks>=80 && marks<=100)
{
return "A";
}
else if (marks>=75 && marks<=79)
{
return "A-";
}
else if (marks>=70 && marks<=74)
{
return "B+";
}
else if (marks>=65 && marks<=69)
{
return "B";
}
else if (marks>=60 && marks<=64)
{
return "B-";
}
else if (marks>=55 && marks<=59)
{
return "C+";
}
else
{
return "null";
}
}
void lines(void)
{ printf("**********************************************************************");
}
Please tell me how can I fixed it.thanks in advanced.
if(p->student_id==search_id){
printf("found");
Now, that's not how you compare strings in C. Use the strcmp() function for string comparison. You may read about strcmp() here.
The issue is your equality check: if(p->student_id==search_id)
Because both student_id and search_id are char arrays, the types will decay to pointers (char *) and this will never work as you expect. Instead, you need to use strcmp (or better, strncmp).
if(strncmp(p->student_id, search_id, 10) == 0) { /* equality */ }
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