#include <stdio.h>
int isMember();
float calculatePrice(int,int,int);
void printPlayer();
char name[4][100];
char name1[100];
int numofplayer, i, numofbook;
int member;
float game, discount, gst, subtotal, total;
int main()
{
i=0;
printf ("Your name: ");
gets (name1);
printf ("No of player: ");
scanf ("%d",&numofplayer);
while (i<numofplayer)
{
printf ("Enter Player %d: ",i+1);
scanf ("%s",name[i]);
i++;
}
printf ("How many game do you want to book?: ");
scanf ("%d",&numofbook);
isMember();
calculatePrice(isMember(),numofbook,numofplayer);
printf ("=======================\n");
printf ("Your booking detail.\n");
printf ("Your name is: %s",name1);
printf ("\nNo of player: %d",numofplayer);
printf ("\nList of player ");
printPlayer();
printf ("\nNo of game: %d",numofbook);
if (isMember()==1)
{
printf ("Status member: member \n");
}
else
{
printf ("Status member: not a member \n");
}
printf ("Total price is (including GST): %.2f",calculatePrice(isMember(),numofbook,numofplayer));
return 0;
}
int isMember()
{
printf ("Are you a member of this club?(1-yes or 0=no): ");
scanf ("%d",&member);
return member;
}
float calculatePrice(int a, int b, int c)
{
game=25;
subtotal=game*c;
subtotal=subtotal*b;
if (a==1)
{
discount=subtotal*0.1;
subtotal=subtotal-discount;
}
gst=0.06*subtotal;
total=subtotal-gst;
return total;
}
void printPlayer()
{
int i;
i=0;
while (i<numofplayer)
{
printf ("%d) ",i+1);
printf ("%s \n",name[i]);
i++;
}
}
Why did it loop at my isMember()?
It keeps looping over and over then it stops, and the other function I am not even confident if it runs correctly.
It doesn't loop.
Instead of keeping the returned value from isMember(), you called it over and over again.
You should define a new variable and save the result in it.
res = isMember();
and use res anywhere you called isMember().
Related
I am writing a program where if the user chooses "2" the program will add a new student record and if he chooses "4" then it will compare his surname with all the other surnames, it will find everyone that has the same surname and print their school information. The problems are the following:
When the user selects "2" my program actually shows all the prompts that are needed and you can input all the information however when I try to print it just gives me 0 0 0.000000 .When it should have given me 2(id) B(name) b(surname) 1(semester) 4(grade).
When the user selects "4" it reads the surname but when it goes to compare it with the others to see if it exists or not it just crashes.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student{
int id;
char name[50];
char surname[50];
int semester;
float grade;
}student;
int main()
{
int x,std,i;
x=0;
int car=0;
int flag=1;
struct student *ptr = NULL;
while (x!=8)
{
printf("\n1. Initialize student list\n2. Add a student record\n3. Delete a student record\n4. Display a student record by student surname\n5. Display students passed\n6. Display students failed\n7. Display all student records\n8. Exit");
printf("\nYour choice: ");
scanf("%d",&x);
if (x==1)
{
printf("How many new students? ");
scanf("%d",&std);
ptr = (student*)malloc(std*sizeof(student));
for(i = 0; i < std; i++){
printf("Enter detail of student #%d\n", (i + 1));
ptr[i].id=i+1;
printf("Enter first name: ");
scanf("%s", ptr[i].name);
printf("Enter last name: ");
scanf("%s", ptr[i].surname);
printf("Enter semester: ");
scanf("%d", &ptr[i].semester);
printf("Enter grade: ");
scanf("%f", &ptr[i].grade);
}
}
else if (x==2)
{
ptr=realloc(ptr,100* sizeof(student));
std=std+1;
ptr[std].id=std+1;
printf("Enter first name: ");
scanf("%s", ptr[std].name);
printf("Enter last name: ");
scanf("%s", ptr[std].surname);
printf("Enter semester: ");
scanf("%d", &ptr[std].semester);
printf("Enter grade: ");
scanf("%f", &ptr[std].grade);
flag=0;
}
else if (x==3)
{
/* code */
}
else if (x==4)
{
printf("Give the surname: ");
const char *sur;
scanf("%s", sur);
for (i = 0; i < std; i++)
{
if(strcmp(sur, ptr[i].surname)==0){
printf("%d ", ptr[i].id);
printf("%s ", ptr[i].name);
printf("%s ", ptr[i].surname);
printf("%d ", ptr[i].semester);
printf("%f ", ptr[i].grade);
printf("\n");
car=1;
}
}
if (car=0)
{
printf("That surname does not exist");
}
}
I may have missed a "{" but this is only part of my code
else if (x==7)
{
for(i = 0; i < std; i++){
printf("%d ", ptr[i].id);
printf("%s ", ptr[i].name);
printf("%s ", ptr[i].surname);
printf("%d ", ptr[i].semester);
printf("%f ", ptr[i].grade);
printf("\n");
}
}
}
}
For when the user chooses "2" everything goes well until its time to print so i tried increasing std by 1 two times.One when the program goes to option "2" and another time when it goes back to main. It didnt do anything so i returned it to how it was in the beginning.
For when the user chooses "4" I tried going with strcmp but it would just throw errors because of sur. I had it written as char sur. After I wrote it as const char *sur it stopped throwing errors but it would just crash when it went to compare it with the other.
I am learning how to create struct's and I am stuck on a program I made. Everything works fine until I try to input "2". When the program prints the symbol it's supposed to be "He" but prints "HeHelium" instead. I can't figure out what's wrong and why it's printing he.symbol and he.name all in one line. Link to image below.
#include <stdio.h>
#include <stdlib.h>
struct Element {
int num;
double mass;
char symbol[2];
char name[20];
};
int main()
{
struct Element h;
h.num = 1;
h.mass = 1.008;
strcpy(h.symbol, "H");
strcpy(h.name, "Hydrogen");
struct Element he;
he.num = 2;
he.mass = 4.0026;
strcpy(he.symbol, "He");
strcpy(he.name, "Helium");
int number;
printf("Please enter the number of the element you want info on. \n");
scanf("%d", &number);
if (number == 1 /*&& !(number > 1)*/) {
printf("Atomic Number: %d \n", h.num);
printf("Atomic Mass: %.3f \n", h.mass);
printf("Atomic Symbol: %s \n", h.symbol);
printf("Atomic Name: %s \n", h.name);
} else if (number == 2) {
printf("Atomic Number: %d \n", he.num);
printf("Atomic Mass: %.3f \n", he.mass);
printf("Atomic Symbol: %s \n", he.symbol);
printf("Atomic Name: %s \n", he.name);
} else {
printf("Invalid number! \n");
printf("Or that element hasn't been added to the date base yet. \n");
printf("Try back later \n");
}
return 0;
}
When I input "2":
You have assigned Element.symbol with only 2byte which can only store string with only one character as the other character will be used for null character. You should write "symbol[3]" as the symbol of elements in periodic table are no longer than 2 characters. Also, your code can become quite messy if you want to assign values for all 118 elements. You can write your code like below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Elements {
int num;
double mass;
char symbol[3];
char name[20];
};
void print(struct Elements element)
{
printf("Atomic Number: %d \n", element.num);
printf("Atomic Mass: %.3f \n", element.mass);
printf("Atomic Symbol: %s \n", element.symbol);
printf("Atomic Name: %s \n", element.name);
}
void assignElement(struct Elements *givenElement, int num, float mass, char symbol[3],
char name[20])
{
givenElement->num=num;
givenElement->mass=mass;
strcpy(givenElement->symbol,symbol);
strcpy(givenElement->name,name);
}
int main()
{
struct Elements element[119];
assignElement(&element[1], 1, 1.008, "H", "Hydrogen");
assignElement(&element[2], 2, 4.06, "He", "Helium");
assignElement(&element[3], 3, 6.09, "Li", "Lithium");
int number;
printf("Please enter the number of the element you want info on. \n");
scanf("%d", &number);
if (number < 119 && number > 0) {
print(element[number]);
}
else {
printf("Invalid number! \n");
printf("Or that element hasn't been added to the date base yet. \n");
printf("Try back later \n");
}
return 0;
}
So in the function getRoster, I have two arrays that are defined in the same way in main and called in the same way. But for some reason, one of the scanf functions write garbage data to the array so that in line 91 (A debugging line in this case) one value is the one I entered and the other is seemingly random. I've checked this code top to bottom already to see if there were any notations that I added to one array and not the other, and I can't seem to find a single one.
#include <stdio.h>
#include <stdlib.h>
void getRoster(int *jerseyNumbers[10], int *playerRatings[10])
{
int i;
for (i=0; i<5; ++i)
{
printf("Enter player %d's jersey number\n", i+1);
scanf("%d", &jerseyNumbers[i]);
printf("Enter player %d's rating\n", i+1);
scanf("%d", &playerRatings[i]);
}
}
void updateRating(int *jerseyNumbers[10], int *playerRatings[10])
{
int i, n = -1, hold;
printf("Enter a jersey number:\n");
scanf("%d", n);
for (i=0; i<5; ++i)
if(jerseyNumbers[i]==n)
hold = n;
if (n=-1);
printf("Error");
printf("Enter a new rating for player:\n");
scanf("%d", &playerRatings[n]);
}
void aboveRating()
{
}
void replacePlayer()
{
}
void outputRoster(int *jerseyNumbers[10], int *playerRatings[10])
{
int i;
for (i=0; i<5; ++i)
{
printf("Player %d -- Jersey number: %d , Rating: %d \n", i+1, jerseyNumbers[i], playerRatings[i]);
}
}
void menu(int *jerseyNumbers[10], int *playerRatings[10])
{
char menuInput;
printf("\nMENU\n");
printf("u - Update player rating\n");
printf("a - Output players above a rating\n");
printf("r - Replace player\n");
printf("o - Output roster\n");
printf("q - Quit\n");
printf("\nChoose an option:\n");
scanf(" %c", &menuInput);
if (menuInput == 'u')
{updateRating(&jerseyNumbers[10], &playerRatings[10]);
}
else if (menuInput == 'a')
{aboveRating();
}
else if (menuInput == 'r')
{replacePlayer();
}
else if (menuInput == 'o')
{outputRoster(&jerseyNumbers[10], &playerRatings[10]);
}
else if (menuInput == 'q')
printf("Reached Quit");
else
printf("Input Error\n");
}
int main()
{
int *jerseyNumbers[10];
int *playerRatings[10];
char menuInput;
int quitFlag = 0;
getRoster(&jerseyNumbers[10], &playerRatings[10]);
printf("%d %d", jerseyNumbers[0], playerRatings[1]);
menu(&jerseyNumbers[10], &playerRatings[10]);
return 0;
}
Refer to #NaveenKumar and #DeiDei's comment to your question.
Actually, the logic of your program is alright. But where you've gone wrong is the syntax regarding how you have declared the arrays and passed them as arguments to the functions. I have listed the changes to be made below:
First of all Dylan, do not declare an array as: int
*jerseyNumbers[10] and int *playerRatings[10]. For the regular array which you actually need, just declare as:
a. *jerseyNumbers and *playerRatings... Remove the size. OR
b. jerseyNumbers[10] and playerRatings[10]... Remove the * from the declaration.
When you're passing these arrays as arguments to a function, don't ever send it how you've done. Just pass the array name as an argument. Like this: getRoster(jerseyNumbers, playerRatings); and menu(jerseyNumbers, playerRatings);.
In the function definition, the parameters representing the array should be either *arrayname or arrayname[size]. Since we have used the first during declaration, use the same here as follows:
void getRoster(int *jerseyNumbers, int *playerRatings) {...},
void updateRating(int *jerseyNumbers, int *playerRatings){...},
void outputRoster(int *jerseyNumbers, int *playerRatings) {...},
void menu(int *jerseyNumbers, int *playerRatings) {...}.
And as #PaulSm4 has suggested don't use the semi-colon at the end of an if conditional. Though this isn't the cause of your problem here, it is a practice you need to follow and mistake to be avoided.
I have attached the working code below, along with the output.
CODE:
#include <stdio.h>
#include <stdlib.h>
void getRoster(int *jerseyNumbers, int *playerRatings)
{
int i;
for (i=0; i<5; ++i)
{
printf("Enter player %d's jersey number\n", i+1);
scanf("%d", &jerseyNumbers[i]);
printf("Enter player %d's rating\n", i+1);
scanf("%d", &playerRatings[i]);
}
}
void updateRating(int *jerseyNumbers, int *playerRatings)
{
int i, n = -1, hold;
printf("Enter a jersey number:\n");
scanf("%d", n);
for (i=0; i<5; ++i)
if(jerseyNumbers[i]==n)
hold = n;
if (n=-1)
printf("Error");
printf("Enter a new rating for player:\n");
scanf("%d", &playerRatings[n]);
}
void aboveRating()
{
}
void replacePlayer()
{
}
void outputRoster(int *jerseyNumbers, int *playerRatings)
{
int i;
for (i=0; i<5; ++i)
{
printf("Player %d -- Jersey number: %d , Rating: %d \n", i+1, jerseyNumbers[i], playerRatings[i]);
}
}
void menu(int *jerseyNumbers, int *playerRatings)
{
char menuInput;
printf("\nMENU\n");
printf("u - Update player rating\n");
printf("a - Output players above a rating\n");
printf("r - Replace player\n");
printf("o - Output roster\n");
printf("q - Quit\n");
printf("\nChoose an option:\n");
scanf(" %c", &menuInput);
if (menuInput == 'u')
{updateRating(jerseyNumbers, playerRatings);
}
else if (menuInput == 'a')
{aboveRating();
}
else if (menuInput == 'r')
{replacePlayer();
}
else if (menuInput == 'o')
{outputRoster(jerseyNumbers, playerRatings);
}
else if (menuInput == 'q')
printf("Reached Quit");
else
printf("Input Error\n");
}
int main()
{
int jerseyNumbers[10];
int playerRatings[10];
char menuInput;
int quitFlag = 0;
getRoster(jerseyNumbers, playerRatings);
printf("%d %d", jerseyNumbers[0], playerRatings[1]);
menu(jerseyNumbers, playerRatings);
return 0;
}
OUTPUT:
Enter player 1's jersey number
1
Enter player 1's rating
10
Enter player 2's jersey number
2
Enter player 2's rating
20
Enter player 3's jersey number
3
Enter player 3's rating
30
Enter player 4's jersey number
4
Enter player 4's rating
40
Enter player 5's jersey number
5
Enter player 5's rating
50
1 20
MENU
u - Update player rating
a - Output players above a rating
r - Replace player
o - Output roster
q - Quit
Choose an option: o
Player 1 -- Jersey number: 1 , Rating: 10
Player 2 -- Jersey number: 2 , Rating: 20
Player 3 -- Jersey number: 3 , Rating: 30
Player 4 -- Jersey number: 4 , Rating: 40
Player 5 -- Jersey number: 5 , Rating: 50
Hope this helps.
STRONG SUGGESTION:
Get in the habit of using curly braces often - even when you don't need them.
void updateRating(int *jerseyNumbers, int *playerRatings)
// You probably only need a pointer or an array - but probably not both ;)
{
int i, n = -1, hold;
printf("Enter a jersey number:\n");
scanf("%d", n);
for (i=0; i<5; ++i) { // Curly brace here...
if(jerseyNumbers[i]==n) { // And here...
hold = n;
}
}
if (n=-1) { // BUG ALERT: deleted ";" (and added a brace)
printf("Error"); // BUG ALERT: fixed this by removing ";"?
} else {
printf("Enter a new rating for player:\n");
scanf("%d", &playerRatings[n]);
}
Or perhaps better:
void updateRating(int *jerseyNumbers, int *playerRatings)
{
int n;
printf("Enter a jersey number:\n");
scanf("%d", n);
printf("Enter a new rating for player:\n");
scanf("%d", &playerRatings[n]);
}
And, as Rishikesh Raje correctly pointed out:
The definition of the array's and the function calls for OP is also
not correct. Please mention this also.
Why does my program close before taking the input for k and then displaying it.
I am writing a code for a menu based program so I need to take input from user after he has entered the information so I can have 1.Print names 2.Exit
while doing this I realized my program didn't take the input and just skipped the part where it is supposed to take value of l from user. So trying to debug it I deleted stuff and came down to this simple program and realized it still wont work any idea why?
#include <stdio.h>
struct student
{
char name[50];
char lname[50];
float marks;
} s[15];
int main ()
{
int i, j,k;
printf("Please enter the number of students:\n");
scanf ("%d", &j);
printf ("Please enter the information for students as asked.\n");
for (i = 0; i < j; i++)
{
scanf ("%s %s %f\n", s[i].name, s[i].lname, &s[i].marks);
}
printf("Please enter a number\n");
scanf ("%d", &k);
printf("your number was %d", k);
return 0;
}
scanf ("%s %s %f\n", s[i].name, s[i].lname, &s[i].marks);
should be
scanf ("%s %s %f", s[i].name, s[i].lname, &s[i].marks);
The \n in scanf just consumes newline char. It will continue consuming newline until a non-newline char is found, which is put back into stdin for the next IO operation
Try this Code
#include<stdio.h>
typedef struct student
{
char name[50];
char lname[50];
int mark;
}S;
int main ()
{
int i, j,k;
printf("Please enter the number of students:\n");
scanf ("%d", &j);
S record[j];
for (i = 0; i < j; i++) {
printf ("Please enter the information for %d student as asked.\n",i+1);
scanf ("%s %s %f",record[i].name, record[i].lname, &record[i].mark);
}
printf("Please enter a number\n");
scanf ("%d", &k);
printf("your number was %d \n", k);
return 0;
}
You were declaring structure student array in the structure declaration itself.you have to declare the array in main function.
Here's my code:
#include <stdio.h>
int validate(int low,int high);
int main ()
{
//Declare Variables
float strength, speed, defense, intelligence;
float strengthRatio, speedRatio, defenseRatio, intelligenceRatio;
int strength_F, speed_F, defense_F, intelligence_F;
float sum;
int luck;
float PStrength=10;
float PDefense=20;
float PIntelligence=40;
int PHP=10;
float EStrength=30;
float EDefense=40;
float EIntelligence=25;
int EHP=10;
int sel;
float attackp;
float magicp;
int low=1;
int high=3;
int Valid_Selection;
//Clear Screen
system("cls");
//Display Logo
printf("+----------------------+\n");
printf("| |\n");
printf("| CODE QUEST |\n");
printf("| |\n");
printf("+----------------------+\n\n");
//Main Menu
printf("--Main Menu--\n");
printf("\n");
printf("1 - New Game\n");
printf("2 - Load Game\n");
printf("3 - Exit\n");
printf("\n");
printf("Selection: \n\n");
//Validate user input using a functuion
Valid_Selection = validate(int low,int high);
//Game_Selection = validate();
printf ("Character Creation \n");
printf ("Please enter your desired stats for your character:\n");
printf ("\n");
printf ("Enter strength: ");
scanf ("%f", &strength);
printf ("Enter speed: ");
scanf ("%f", &speed);
printf ("Enter defense: ");
scanf ("%f", &defense);
printf ("Enter intelligence: ");
scanf ("%f", &intelligence);
//Calculate the sum of all attributes
sum = strength + speed + defense + intelligence;
//Calculate ratios for each attribute
strengthRatio = strength / sum;
speedRatio = speed / sum;
defenseRatio = defense / sum;
intelligenceRatio = intelligence / sum;
//Calculate the final Stats as whole number
strength_F = strengthRatio * 100;
speed_F = speedRatio * 100;
defense_F = defenseRatio * 100;
intelligence_F = intelligenceRatio * 100;
//Calculate the player's luck
luck = (int)sum % 30;
//Create an empty line for beauty
printf ("\n");
//Display to the user the finalized player stats
printf ("Your player's final stats are:");
printf ("\n");
printf ("Strength: %d\n", strength_F);
printf ("Speed: %d\n", speed_F);
printf ("Defense: %d\n", defense_F);
printf ("Intelligence: %d\n", intelligence_F);
printf ("Luck: %d\n", luck);
//Display "Battle Starts"
printf("Battle Start!\n\n");
while (PHP>=0 && EHP>=0) {
//Display user and enemy HP and asks user which attack execute
printf("Your HP: %d, Enemy HP: %d\n", PHP, EHP);
printf("1 - Attack Power\n");
printf("2 - Magic Power\n");
scanf("%d",&sel);
//Option 1, Option 2
if (sel==1){
attackp = (PStrength/EDefense)*5;
EHP = EHP - attackp;
printf("You Attacked The Enemy\n");
}
else{
magicp = (PIntelligence/EIntelligence)*5;
EHP = EHP - magicp;
printf("You bewitched the enemy!\n");
}
//Enemy reaction based on his own HP
if (EHP<=0)
printf("You Won!\n");
else {
attackp = (EStrength/PDefense)*5;
PHP = PHP - attackp;
printf("The Enemy Attacked You\n");
}
//Indicates if user lost the game
if (PHP<=0)
printf("You Lost!\n");
printf("\n");
}
return 0;
}
int validate(int low, int high) {
int s;
do{
scanf("%d", s);
if (s<1 || s>3)
printf("innvalid Input, try again:");
} while (s<1 || s>3);
return s;
}
int validate(int low, int high) {
int selection;
do {
scanf("%d", selection);
if (selection <0 || selection>3)
printf("Invalid Input, try again: ");
} while (0<selection<4);
return selection;
}
I want the user to enter a number between 1 and 3 and I need the validate function to verify it. Can anyone explain me where I go wrong please? what is the proper way to do it?
Your validate must be called as:
//Validate user input using a functuion
Valid_Selection = validate(1, 3);
as your menu has choices between 1 and 3, and your function should be:
int validate(int low, int high) {
int s=0;
char buf[128];
do {
if (fgets(buf,128,stdin)==0 || sscanf(buf, "%d", &s)!=1 || (s<low || s>high))
printf("invalid Input, try again:");
else
return s;
} while (1);
}
and there can be only one function with that name, so remove the second one. Btw, while (0<selection<4) in the second one, must be written as: while (0<selection && selection<4).
Edit: note the check for the return value of sscanf. It tells us whether sscanf could read the value type specified, %d, and note to pass the address of the integer where to store the result. The initialization of s to zero ensures the while loop will not be exited while there was invalid input.
Edit: fixed Chux's comment to consume stdin.