I am doing a program that is a customer order application. Basically it is a database (like e-bay) where a customer must be registered in the system to buy a product. The problem I am currently having is when I come to modify a customer.
Basically when I run the program I have a menu. I choose customer and I have a sub-menu and I choose to modify the customer data. then it asks me for an id and the program checks whether it is valid or not. If the id number is valid it goes on to let you choose which criteria you want to modify. After the modification of that criteria it prints out ~~~ITEM EDITED~~~ and then it just like freeze. Nothing comes afterwards and I have to terminate the program myself.
This happens as well when an invalid id is entered. When this happens it prints out the main menu and when I enter a number to choose from the main menu nothing happens.
I tried solving it myself but cannot find the problem. I tried to use exit(0) instead of break; after the cases but same problem happened. Here under is the code of the modify function. Just to let you know that I have a header file with all the necessary information such as structure declaration.
modify_customer()
{
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
char another;
int flag = 0;
int choice;
char x[8];
FILE *pCust;
int size;
printf("\nENTER CUSTOMER ID NUMBER: ");
//fflush(stdout);
scanf("%s",x);
flag = checkcustomer(x);
if(flag==0)
{
pCust=fopen("customer.txt","r+b");
rewind(pCust);
while(fread(&cust,sizeof(cust),1,pCust))
{
if(strcmp(cust.id,x)==0)
{
printf("\nid ==> %s",cust.id);
printf("\nname ==> %s",cust.name);
printf("\nsurname ==> %s",cust.surname);
printf("\naddress ==> %s",cust.address);
printf("\nDO YOU WANT TO EDIT THIS REDORD [Y/N]: ");
scanf("%s", &another);
fflush(pCust);
if(another=='Y'|| another=='y')
{
printf("\n(1) EDIT ID NUMBER");
printf("\n(2) EDIT NAME");
printf("\n(3) EDIT SURNAME");
printf("\n(4) EDIT ADDRESS");
printf("\nenter choice (1) - (4) to edit: ");
//fflush(stdout);
scanf("%d",&choice);
switch(choice)
{
case 1 : printf("\nEDIT RECORD [ID]");
printf("\nenter new customerID:");
scanf("%s",cust.id);
size = sizeof(cust);
fseek(pCust,-size,SEEK_CUR);
fwrite(&cust,sizeof(cust),1,pCust);
break;
case 2 : printf("\nEDIT RECORD [NAME]");
printf("\nenter new name: ");
//fflush(stdout);
scanf("%s",cust.name);
size = sizeof(cust);
fseek(pCust,-size,SEEK_CUR);
fwrite(&cust,sizeof(cust),1,pCust);
break;
case 3 : printf("\nEDIT RECORD [SURNAME]");
printf("\nenter new surname: ");
//fflush(stdout);
scanf("%s",cust.surname);
size = sizeof(cust);
fseek(pCust,-size,SEEK_CUR);
fwrite(&cust,sizeof(cust),1,pCust);
break;
case 4 : printf("\nEDIT RECORD [ADDRESS]");
printf("\nenter new address: ");
//fflush(stdout);
scanf("%s",cust.address);
size = sizeof(cust);
fseek(pCust,-size,SEEK_CUR);
fwrite(&cust,sizeof(cust),1,pCust);
break;
}
printf("\n~~~ITEM EDITED~~~");
break;
}
else
{
printf("\nRECORDS ARE NOT MODIFIED");
customer_menu();
}
}
}
}
if(flag==1)
{
printf("\nITEM DOES NOT EXIST. TRY AGAIN");
main_menu();
}
fflush(stdout);
getch();
fclose(pCust);
return 0;
}
Related
I'm making a c program for a simple library but for some reason the program keeps crashing right on startup. Like there's a menu that is displayed but it doesn't even appear it just crashes. can any one help me?
struct library
{
char name[50];
int id;
int qty;
}books[50],copy[50],delet[50],sort[50];
int i=0;
FILE *mybooks;
int main()
{
int choice; char ans;
int id;
int qty;
int s,o=0,j=0;
char name[50];
mybooks=fopen("D:\\mybooks.txt","r");
if (mybooks == NULL) printf("Error. File not found.");
else
{
while(!feof(mybooks))
{
fscanf(mybooks,"%[^\n] %d %d",books[i].name,&books[i].id,&books[i].qty);
strcpy(copy[i].name,books[i].name);
copy[i].id=books[i].id;
copy[i].qty=books[i].qty;
i++;
}
fclose(mybooks);
}
printf("Welcome to the Library.\n");
do
{
printf("Please choose an option:\n");
printf("1.Insert a book\n");
printf("2.Delete a book\n");
printf("3.Search a book by ID\n");
printf("4.Search a book by name\n");
printf("5.Display all books (sorted by name)\n");
printf("6.Display all books (unsorted)\n");
scanf("%d",&choice);
switch (choice){
case 1:
printf("You will need to enter a name, ID, and quantity of the book.\n");
printf("please enter book name:");
fflush(stdin);
fgets(name,sizeof name,stdin);
printf("please enter book ID:");
scanf("%d",&id);
printf("please enter book quantity:");
scanf("%d",&qty);
InsertBook(name,id,qty);
printf("your book has been added successfully\n");
break;
case 2:
printf("Please enter book ID:");
scanf("%d",&id);
DeleteBook(id);
printf("book successfully deleted.\n");
break;
case 3:
printf("Please enter ID of Book:");
scanf("%d",&id);
s=LinearSearch(id,j);
if (s>=0)
{
printf("Book Found.\n");
printf("Name:%s",books[s].name);
printf("ID:%d\n",books[s].id);
printf("Quantity:%d\n",books[s].qty);
}
else
printf("Sorry, the book doesn't exist.\n");
break;
case 4:
printf("Please enter name of book:");
fflush(stdin);
gets(name);
sorting();
s=BinarySearch(name,0,i);
printf("Book Found.\n");
printf("ID:%d\n",sort[s].id);
printf("Quantity:%d\n",sort[s].qty);
break;
case 5:
sorting();
while (o<i);
{
printf("%s\n",sort[o].name);
o++;
}
printf("\n");
break;
case 6:
while(o<i)
{
printf("%s",books[o].name);
o++;
}
break;
default:
printf("Invalid Choice. Please try again.\n");
break;
}
printf("do you want to choose another option?(y/n) ");
scanf(" %c",&ans);
}while(ans == 'y');
}
(I'm using functions for the library but I don't think they are causing any problem since i didn't call them yet.)
edited the question to add the structure
You have tested an end of file condition before performing any i/o on the input file. And then, when you perform the i/o with fscanf(), you did not test the result to see if the variables were successfully read.
What is happening is that scanf() is probably failing and you do not reach the end of the loop, i.e., the EOF condition. You get stuck in there until one of your assignments (strcpy(copy[i].name,books[i].name);, copy[i].id=books[i].id; or copy[i].qty=books[i].qty;) will finally cause an overflow.
To verify this, run the code in a debugger.
Using fscanf() is very tricky, always test it thoroughly.
I've been trying to do a leaderboard program for school, but I've noticed that the program overwrites the first player when trying to add new ones.
Am I doing something wrong?
The code accepts the players just fine, but opposed to adding new players to the leader board it just overwrites the first one completely.
#include <stdio.h>
int number,i,key,newscore,a;
struct playerdata
{
char fname[50],lname[50];
int id,score;
}playerstats[5];
void welcome()
{
printf("\nWelcome to the leaderboard, challenger!");
printf("\nPlease select an option:");
printf("\n1-Add 5 players at a time\n2-Display all stats\n3-Update score\n4-Show player ranking\n5-Add 1 player");
printf("\n\n");
scanf("%d",&number);
switch(number)
{
case 1:
fillplayer();
break;
case 2:
displaystats();
break;
case 3:
updatescore();
break;
case 4:
playerranking();
break;
case 5:
addplayer();
break;
default:
printf("\nThis option is invalid");
}
}
void fillplayer() //read player info//
{
for(int i=0;i<5;i++)
{
printf("\nPlease enter your first name.");
scanf("%s", &playerstats[i].fname);
printf("\nPlease enter your last name.");
scanf("%s", &playerstats[i].lname);
printf("Please enter your player ID (Any random 4 digit number)");
scanf("%d",&playerstats[i].id);
printf("\n Please enter your score");
scanf("%d",&playerstats[i].score);
}
}
void displaystats() //Output player info//
{
printf("\nFirstName\tLast Name\tID\tScore\t");
for(int i=0;i<5;i++)
{
printf("\n%s\t\t%s\t\t%d\t\t%d",playerstats[i].fname,playerstats[i].lname,playerstats[i].id,playerstats[i].score);
}
}
void addplayer() //read one player's info//
{
printf("\nPlease enter your first name.");
scanf("%s", &playerstats[i].fname);
printf("\nPlease enter your last name.");
scanf("%s", &playerstats[i].lname);
printf("Please enter your player ID (Any random 4 digit number)");
scanf("%d",&playerstats[i].id);
printf("\n Please enter your score");
scanf("%d",&playerstats[i].score);
}
int searchplayer(void)
{
printf("\nEnter your player ID");
scanf("%d", &key);
{
if (playerstats[i].id=key)
{
return a;
}
else
{
return -1;
}
}
}
void updatescore()
{
a=searchplayer();
if (playerstats[i].id==key)
{
printf ("\nYour ID is%d", playerstats[i].id);
printf("\nEnter your new high score");
scanf("%d",&newscore);
if (newscore>playerstats[i].score)
{
playerstats[i].score=newscore;
printf("Score successfully changed to %d", newscore);
}
else
{
printf("\nThis score is less than your current highscore, the high score shall not be changed");
}
}
else
{
printf("\nInvalid ID");
}
}
void playerranking()
{
printf("\n not done");
}
int main()
{
for(int i=0;i<999;i++)
{
welcome();
}
return 0;
}
You have a local loop counter i inside the function main() and some other function.
You have a (not explicitly initialised) global variable i which is used inside other functions.
They are not the same.
You never change the global i, which is e.g. used in the relevant function addplayer().
To solve I recommend to:
define to yourself the meaning and use of the global variable
name it accordingly
introduce some way of changing it, maybe more options in the menu
use it as parameter to called functions
also use it in the function which adds 5 players at once (or that will always overwrite the same first five), i.e. use the sum of global "current" and local loop counter
quite hard, but probably what you want: use the global via pointer parameter in functions which are supposed to change it; e.g. especially the add5 function
consider all the globals; generally try to avoid globals, they got you into the trouble you are currently experiencing
Source outline: User selects option either to 1. Make Bugatti; 2. Create Bugatti; or 3. Exit program. After each option is complete, the user should be returned back to the menu to select another option.
(Note: the user cannot display the car until it is created, hence the if statement in case 2)
The problem: User's inputs for createCar() function are not being returned back into main() (specifically to case 2 - Display Bugatti) and is displaying some large, odd values, instead of the user's inputs. I know it has something to do with the values not being stored into memory/called back to main().
Also, the while statements in createCar() function are completely being disregarded when I use parameters for some reason.
I would appreciate answers in code to make things easier to resolve personally if possible, thanks!
#include <stdio.h>
#include <math.h>
#define now 2017
//Function headers
void printMenu(void);
void createCar(int *speed, int *year, int *bhp, int *age);
int main(void)
{
//Variables
int userInput;
int topSpeed, yearMade, horsepower, carAge;
/***Loop program to return to menu after option is completed***/
for(;;)
{
//Print menu and get input from user
printMenu();
scanf("%i", &userInput), fflush(stdin);
//Validate input
while(userInput < 1 || userInput > 3)
{
printf("\nWrong input, please retry...\n");
scanf("%i", &userInput), fflush(stdin);
}
//Make decisions after user's choice
switch(userInput)
{
//Option 1: Create car then return to menu
case 1:
createCar(&topSpeed, &yearMade, &horsepower, &carAge);
continue;
//Option 2: Read car details (if created) then return to menu
case 2:
if(topSpeed == NULL)
{
printf("\nYou must first create a car, please retry...\n\n");
continue;
}
printf("\n----Bugatti Veyron----\n");
printf("Top Speed: %i km/h\nYear made: %i\nAge: %i years old\nHorsepower: %i bhp\n", &topSpeed, &yearMade, &horsepower, &carAge);
printf("----------------------\n");
continue;
//Option 3: Kill program
case 3:
exit(1);
}
}
return 0;
}
//Function: Display menu
void printMenu(void)
{
printf("-----------------------------------------\n");
printf("[Bob's Custom Car Creation Complex v1.0]\n");
printf("1. Create Bugatti\n2. Display Bugatti\n3. Exit\n");
printf("-----------------------------------------\n");
}
//Function: Make a car + validate inputs
void createCar(int *speed, int *year, int *bhp, int *age)
{
//Prompt user for top speed + validate input
printf("Enter the top speed of your Bugatti:");
scanf("%i", &speed), fflush(stdin);
while(speed <=0)
{
printf("You cannot have a top speed of nothing silly :-D\nPlease retry...\n");
scanf("%i", &speed), fflush(stdin);
}
//Prompt user for year mate + validate input
printf("What year is your Bugatti produced?:");
scanf("%i", &year), fflush(stdin);
while(year <=0)
{
printf("You cannot own a Bugatti that is from the future laddy!!\nPlease retry...\n");
scanf("%i", &year), fflush(stdin);
}
//Calculate age of car
age = now - year;
//Prompt user for horsepower + validate input
printf("How much horsepower does your Bugatti have?:");
scanf("%i", &bhp), fflush(stdin);
while(bhp <=0)
{
printf("A Bugatti with no engine... doesn't sound too promising :-O\nPlease retry...\n");
scanf("%i", &bhp), fflush(stdin);
}
}
You have to dereference the age and year pointer to get/set its value.
//Calculate age of car
*age = now - *year;
You have to remove the '&' at the scanf() in createVar, because speed, year and bhp are already pointers to int.
Enabling compiler warnings and resolving them would avoid you troubles!
I've written this c program to insert, view, modify and delete the records in a file. File name is emp.dat. The code for displaying, adding and deleting is working fine but the modify part is not working. The program asks to input details to modify but nothing gets updated/modified.
The Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
void main()
{
FILE *outp,*inpt;
char another,choice;
struct emp
{
int emp_no,age;
char name[40];
float bs;
};
struct emp e;
char empname[40];
long int recsize;
outp=fopen("emp.dat","r+");
if(outp=='\0')
{
outp=fopen("emp.dat","w+");
if(outp=='\0')
{
puts("cannot open file\n");
exit(1);
}
}
recsize=sizeof(e);
while(1)
{
printf("1.Add records\n");
printf("2.List records\n");
printf("3.Modify records\n");
printf("4.Delete records\n");
printf("0. exit\n");
printf("Your choice\n");
fflush(stdin);
choice=getche();
switch(choice)
{
case '1': //code to add data
.
case '2': //code to display data
case '3': //code to modify data
another='Y';
while(another=='Y')
{
printf("\nEnter name of employee to modify");
scanf("%s",empname);
rewind(outp);
while(fread(&e,recsize,1,outp)==1)
{
if(strcmp(e.name,empname)==0)
{
printf("\nenter new name,age & gs");
scanf("%d %s %d %f",&e.emp_no,&e.name,&e.age,&e.bs);
fseek(outp,-recsize,SEEK_CUR);
fwrite(&e,recsize,1,outp);
break;
}
}
printf("\nModify another record(Y/N)");
fflush(stdin);
another=getche();
}
printf("\n\n");
break;
case '4': //code to delete data
case '0':
fclose(outp);
printf("\n\n");
exit(1);
}
}
}
As can be seen in output the name doesn't change from Zaid to Cow, so does the age and gs
You really should test the return values.
The prompt asks for name,age & gs, and you enter them as asked. However scanf is instructed to get an integer (emp_no) first ("%d %s %d %f"). Missing that it fails immediately and nothing gets updated.
The situation is easily detectable: scanf returns the number of successful conversions.
The following code is a project I'm working on and after entering the details as in name and email it won't go to the next part of the code which is printing the price and then go to the next function. What did I do wrong??
Also, what can I do so that a customer can enter their details with spacing?
Thanks in advance.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int option,card_num,csc,phone_number;
char name,address,e_mail,registration;
void membership();
void payment();
int main()
{
membership();
return 0;
}
void membership()
{
printf("\tTHE CRUMP'S MEMBERSHIP");
printf("\n\n This membership ...");
printf("\n\n REGISTRATION [CONTRACTOR(A)/CORPORATION(B)]=");
scanf("%c",®istration);
switch (registration)
{
case 'A':
printf("\n\nEnter details without any spacing.");
printf("\nNAME:");
scanf("%s",&name);
printf("\nADDRESS:");
scanf("%s",&address);
printf("\nPHONE NUMBER:");
scanf("%d",&phone_number);
printf("\nE-MAIL:");
scanf("%s",&e_mail);
break;
case 'B':
printf("Enter details without any spacing.");
printf("\nNAME OF CORPORATION:");
scanf("%s",&name);
printf("\nADDRESS OF CORPORATION:");
scanf("%s",&address);
printf("\nPHONE NUMBER OF CORPORATION:");
scanf("%d",&phone_number);
printf("\nE-MAIL OF CORPORATION:");
scanf("%s",&e_mail);
break;
}
if (registration=='A')
printf("\n THE REGISTRATION FEE = |RM 50/MONTH |\t| RM 500/YEAR|");
else if (registration=='B')
printf("\n THE REGISTRATION FEE = |RM 200/MONTH |\t| RM 2200/YEAR|");
}
void payment()
{
printf("\n\nChoose method of payment: ");
printf("\n\t 1- Money Transfer \n\t 2-Debit Card\n");
scanf("%d",&option);
if (option==1)
{
printf("\nYou have chosen Money Transfer.");
printf("\nYou can transfer your money at our bank account --> 4365 4200 1471");
printf ("\n your membership will be confirmed when we have received the payment");
printf("\n************************************************************");
if (registration=='A')
{
printf("\nNAME:%s",name);
printf("\nADDRESS:%s",address);
printf("\nPHONE NUMBER:%d",phone_number);
printf("\nE-MAIL:%s",e_mail);
}
else if (registration=='B')
{
printf("\nNAME OF CORPORATION:%s",name);
printf("\nADDRESS OF CORPORATION:%s",address);
printf("\nPHONE NUMBER OF CORPORATION:%d",phone_number);
printf("\nE-MAIL OF CORPORATION:%s",e_mail);
}
printf("\n\n your transaction completed...\n\n Enjoy your membership discount.");
}
else if (option==2)
{
printf("\nYou have chosen Credit/Debit card.");
printf("\n Please enter your Credit/Debit card number:");
scanf("%d",&card_num);
printf("\n Please enter CSC code:");
scanf("%d",&csc);
printf("\nYour membership will be confirmed when we have received the payment");
printf("\n*********************************************************\n\n");
if (registration=='A')
{
printf("\nNAME:%s",name);
printf("\nADDRESS:%s",address);
printf("\nPHONE NUMBER:%d",phone_number);
printf("\nE-MAIL:%s",e_mail);
}
else if (registration=='B')
{
printf("\nNAME OF CORPORATION:%s",name);
printf("\nADDRESS OF CORPORATION:%s",address);
printf("\nPHONE NUMBER OF CORPORATION:%d",phone_number);
printf("\nE-MAIL OF CORPORATION:%s",e_mail);
}
printf("\n\n Your transaction is completed...\n\n Enjoy your membership discount.");
}
}
You are trying to read strings into char variables:
char name,address,e_mail,registration;
//...
scanf("%s",&name);
char only holds one character, not a string. If you want to read a string use an character array:
char name[100];
//...
and pass it to scanf like this:
scanf("%s",name);
because the array already decays to a pointer and taking the address is unnecessary.
Note that this requires you to set a limit for the name length. For example I choose 100-1 = 99 characters as limit. If the input is longer, undefined behaviour occurs, which is what you are experiencing right now.
Also note that you never call payment, so this will never be executed. If you want it to be executed after membership, then you need to call it:
int main()
{
membership();
payment();
return 0;
}
Your program has no call to payment() function thats why the program flow is not complete.