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
Related
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 want to show the availability of the seats in linked list, but I don't know somehow the logic in the chekcavailability() doesn't work.
First input is okay, the second input when I entered the same value it shows seat has been taken and return back to the particular function.
But when I enter again the different value which is available, it gives me an error.
Please help thank you.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define A 20
struct passenger
{
char name[20];
char booking_id[20];
char passno[20];
char seatno[20];
struct passenger *next;
}*start,*curr;
void datainput(), savefile(), loadfile(), checkavailability(), validationseat();
int main()
{
void reserve_seat(), cancel_seat(), modify_seat(), display_layout(), exit();
int choice;
start=curr=NULL;
do
{
system("cls");
printf("\n\n*************************************************");
printf("\n\n********AIRLINE RESERVATION MENU*****************");
printf("\n\n*************************************************");
printf("\n\n\t\t* 1. Reserve seat *");
printf("\n\n\t\t* 2. Modify seat *");
printf("\n\n\t\t* 3. Cancel seat *");
printf("\n\n\t\t* 4. Display seat layout*");
printf("\n\n\t\t* 5. Exit *");
printf("\n\n*************************************************");
printf("\n\n\n\n\t\t Enter your choice: ");
scanf("%d",&choice);fflush(stdin);
switch (choice)
{
case 1:
reserve_seat();
break;
case 2:
modify_seat();
break;
case 3:
cancel_seat();
break;
case 4:
display_layout();
break;
case 5:
{
exit();
break;
}
default:
printf("invalid choice!!, please try again");
}
getch();
}while (choice != 5);
}
void datainput()
{
printf("\n\t\t enter your booking ID: ");
gets(curr->booking_id); fflush(stdin);
printf("\n\t\t enter your seat number: ");
gets(curr->seatno); fflush(stdin);
printf("\n\t\t Enter Name: ");
gets(curr->name); fflush(stdin);
printf("\n\t\t Enter Passport Number: ");
gets(curr->passno); fflush(stdin);
}
void reserve_seat()
{
curr=start;
checkavailability();
if(start==NULL)
{
start=curr=(struct passenger *)malloc(sizeof(struct passenger));
datainput();
curr->next=NULL;
printf("\n\t data has been recorded");
return;
}
while(curr->next=NULL)
curr=curr->next;
curr->next=(struct passenger *)malloc(sizeof(struct passenger));
curr=curr->next;
datainput();
curr->next=NULL;
printf("\n\t data has been recorded");
void checkavailability()
{
int i;
char cmp3[20];
printf("select your seat(1-20)");
gets(cmp3);fflush(stdin);
while(curr)
{
if (strcmp(curr->seatno, cmp3)==0)
{
printf("Seat has been taken\n");
checkavailability();
}
else
{
break;
}
}
printf("seat available");
return;
}
There are many error with your code, and the worst is that he cannot compile (unless conio declare an exit function with no parameter).
First, you need to activate a decent compiler option. At least -Wall -Wextra (depend of the compiler).
In main function, this : exit();
The exit function need a parameter. Fix that.
modify_seat();
cancel_seat();
display_layout();
These function aren't implemented, so you shouldn't make a call to them. Fix that either.
Do not use gets ! It's dangerous and unsafe.
Do not fflush(stdin) ! It's undefined behavior.
The "A" define is useless and not really explicite. What was it supposed to be ? "Array" ?
For your safety, try to not use global variable.
I suggest to define a structure and declare a variable in main.
In "reserve_seat" :
while(curr->next=NULL)
you made a mistake here : it's while(curr->next != NULL)
You assign NULL to curr->next, maybe it's the reason that why your linked list is broken.
Well, it's a dirty code for me, because it severly lack rigourous coding.
For example, check if your function call failed (like malloc).
I suggest you to rewrite the code.
I have an assignment to write a program for supporting an art gallery in C. It has to be menu based program using lists. I wrote the first function of the menu and I need some help writing the other three. So I have a structure of an unique code of the painting, author's name, painting's name, price, year of the painting. I have to create a function deleting a painting using the unique code, print out all the info about every painting and modifying a painting again using said code. The data has to be in a dynamic type structure using a linked list. This is the program so far.
#include <stdio.h>
void addPainting(void);
void erasePainting(void);
void printData(void);
void modifyData(void);
int main()
{
struct paintings
{
char code[20];
char name[50];
char paintingName[50];
double price;
int year;
}painting[100];
int choice;
do
{
printf("Menu\n");
printf("To add a painting press 1.\n");
printf("To erase a painting press 2.\n");
printf("To print data for all paintings by authors alphabetically press 3.\n");
printf ("To modify data for a painting press 4.\n");
printf("To exit the program press 5.\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
addPainting();
break;
}
case 2:
{
erasePainting();
break;
}
case 3:
{
printData();
break;
}
case 4:
{
modifyData();
break;
}
default: printf ("Wrong choice. Try again\n");
break;
}
}while (choice !=5);
void addPainting()
{
FILE *fp;
struct paintings painting;
printf("Enter code:");
scanf("%s", &painting.code);
printf("Enter the name of the author:");
scanf("%s", &painting.name);
printf("Enter the name of the painting:");
scanf("%s", &painting.paintingName);
printf("Enter price:");
scanf("%lf", &painting.price);
printf("Enter the year of creation:");
scanf("%d", &painting.year);
if ((fp=fopen("paintings","wb"))==NULL)
exit(1);
if ((fwrite (&painting,sizeof(painting),1,fp)!=1))
exit(2);
fclose(fp);
}
}
First problem: You are missing the closing brace ( } ) for the main() function. (but I am sure you knew that)
The reason for the struct size error is that you are attempting to create an instance of struct painting in the void addPainting() function, when it was created with local scope in the main function, and therefore it is not visible to the function. Create struct painting with global scope if you want to use it this way:
This will build (and run) but only for the functions defined, the others are commented out. There are other problems you will have to work out, or ask about.
EDITED to fix scanf() statements, show use of fopen()/fclose(), create and write strings using sprintf()/fputs()...
void addPainting(void);
//void erasePainting(void);
//void printData(void);
//void modifyData(void);
typedef struct //created with global scope, visible to all functions
{
char code[20];
char name[50];
char paintingName[50];
double price;
int year;
}PAINTING;
PAINTING painting[100];//array of instance of PAINTING
#define PATH "C:\\play\\painting.txt" //edit to your need
int main()
{
int choice;
do
{
printf("Menu\n");
printf("To add a painting press 1.\n");
printf("To erase a painting press 2.\n");
printf("To print data for all paintings by authors alphabetically press 3.\n");
printf ("To modify data for a painting press 4.\n");
printf("To exit the program press 5.\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
addPainting();
break;
}
case 2:
{
//erasePainting();
break;
}
case 3:
{
//printData();
break;
}
case 4:
{
//modifyData();
break;
}
default: printf ("Wrong choice. Try again\n");
break;
}
}while (choice !=5);
}
void addPainting(void)
{
FILE *fp;
char stringToWrite[80];
//Note: this function could be prototyped with an int argument
// to be used as an index for the array arguments of your
// structure. Currently, the indexes are hard-coded to 0,
printf("Enter code:");
//scanf("%s", &painting[0].code);
scanf("%s", painting[0].code); //& not needed for char array (char *) et. al.
printf("Enter the name of the author:");
scanf("%s", painting[0].name);
printf("Enter the name of the painting:");
scanf("%s", painting[0].paintingName);
printf("Enter price:");
scanf("%lf", &painting[0].price);
printf("Enter the year of creation:");
scanf("%d", &painting[0].year);
fp = fopen (PATH, "a");//open for create/append text file (not write binary, "wb")
if(fp)
{
sprintf(stringToWrite, "Painting Code is: %s\n", painting[0].code);
fputs(stringToWrite, fp);
// do others same way...
//...
fclose(fp);
}
}
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.
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;
}