Is there a function similar to string compare but for integers? - c

I want to allow the user to enter a variable amount, and then compare that amount to my array of percentages. And then display ALL amounts in my percentages array equal to OR greater than that number the user entered. I would also like to do this for a lower amount, but they should be the same I would think. If anyone can provide any insight I would appreciate it! Code will be attached underneath.. (Please let me know if I can clarify anything)
/*
10/31/2017
FOOTBALL STATS
*/
#include <stdio.h>
#define NUM_TEAM 30
#define LEN_NAME 40
void displayWelcome(void);
void calcPercent(double percentages[], int elements, int wins[], int losses[], int ties[]);
void showAll (char name[], char league[], char division[], int wins, int losses, int ties, double percentages);
void displayExit(void);
int main (void)
{
//Display welcome message
displayWelcome();
char name[NUM_TEAM][LEN_NAME] = {0};
char division[NUM_TEAM][LEN_NAME] = {0};
char league[NUM_TEAM][LEN_NAME] = {0};
char line[LEN_NAME];
char menu, again;
int wins[NUM_TEAM] = {0};
int losses[NUM_TEAM] = {0};
int ties[NUM_TEAM] = {0};
int i = 0, count, sum, percentQuery;
double percentages[NUM_TEAM] = {0};
;
FILE * filePtr;
filePtr = fopen("C:\\Users\\thoma\\NFLTeams.txt", "r");
if (filePtr == NULL)
{
printf("Unable to open file\n");
}
else
{
while (i < NUM_TEAM && fgets( line, sizeof(line), filePtr) != NULL)
{
sscanf(line, "%s%s%s%i%i%i",name[i], league[i], division[i], &wins[i], &losses[i], &ties[i]);
i++;
}
fclose(filePtr);
count = i;
}
//^ end reading in file
//Calculate win percentages
calcPercent( percentages, count, wins, losses, ties);
//Main menu loop
do
{
//Ask user how they would like to search
printf("Please choose an option from the following menu:"
"\n-Enter 'a' to display all information contained in the database"
"\n-OR Enter 'b' to search by league"
"\n-OR Enter 'c' to search by division"
"\n-OR Enter 'd' to search by wins above a certain percentage"
"\n-OR Enter 'e' to search by wins below a certain percentage: ");
scanf("\n%c", &menu);
//If user chooses a
if (menu == 'a')
{
//Display all of database
for (i = 0; i <= count - 1; i = i + 1)
{
showAll(name[i], league[i], division[i], wins[i], losses[i], ties[i], percentages[i]);
}
}
//If user chooses b
else if (menu == 'b')
{
// Propmt user to choose AFC or NFC
printf("\nPlease choose from the following menu:\nEnter 'a' to search for teams in the AFC league \nOR enter 'b' to search for teams in the NFC league: ");
// scan for what the user entered
scanf("\n%c", &menu);
//Display option for AFC
if (menu == 'a')
{
for (i = 0; i < count; i = i + 1 )
{
if (strcmp (league[i], "AFC") == 0)
{
printf("Here are the standings for the teams in the AFC division:\n");
printf("Team Name: %s \nLeague: %s\nDivision: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name[i], league[i], division[i], wins[i], losses[i], ties[i], percentages[i]);
}
}
}
else
//Display option for NFC
{
for (i = 0; i < count; i = i + 1 )
{
if (strcmp (league[i], "NFC") == 0)
{
printf("Here are the standings for the teams in the NFC division:\n");
printf("Team Name: %s \nLeague: %s\nDivision: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name[i], league[i], division[i], wins[i], losses[i], ties[i], percentages[i]);
}
}
}
}
//If user chooses c
else if (menu == 'c')
{
printf("\nPlease choose an option from the following menu: \nEnter 'a' if you would like to search for North division standings\n"
"OR enter 'b' to search for East division standings\nOR enter 'c' to search for South division standings\nOR enter"
" 'd' to search for West division standings: ");
scanf("\n%c", &menu);
if (menu == 'a')
{
for (i = 0; i < count; i = i + 1 )
{
if (strcmp (division[i], "North") == 0)
{
printf("Here are the standings for the teams in the North division:\n");
printf("Team Name: %s \nLeague: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name[i], league[i], wins[i], losses[i], ties[i], percentages[i]);
}
}
}
else if (menu == 'b')
{
for (i = 0; i < count; i = i + 1 )
{
if (strcmp (division[i], "East") == 0)
{
printf("Here are the standings for the teams in the East division:\n");
printf("Team Name: %s \nLeague: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name[i], league[i], wins[i], losses[i], ties[i], percentages[i]);
}
}
}
else if (menu == 'c')
{
for (i = 0; i < count; i = i + 1 )
{
if (strcmp (division[i], "South") == 0)
{
printf("Here are the standings for the teams in the South division:\n");
printf("Team Name: %s \nLeague: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name[i], league[i], wins[i], losses[i], ties[i], percentages[i]);
}
}
}
else if (menu == 'd')
{
for (i = 0; i < count; i = i + 1 )
{
if (strcmp (division[i], "West") == 0)
{
printf("Here are the standings for the teams in the West division:\n");
printf("Team Name: %s \nLeague: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name[i], league[i], wins[i], losses[i], ties[i], percentages[i]);
}
}
}
}
//if user chooses d
else if (menu == 'd')
{
/* UNFINISHED.. COULD NOT FIGURE OUT SYNTAX
My goal was to compare my percentages array to the value that the user inputted (which was stored in the variable 'percentQuery' and display values that were greater than or equal to my percent
Query
printf("In this menu, you may search for a win percentage above a certain amount.\n"
"Please enter the amount you would like to search ABOVE: ");
scanf("\n%d", &percentQuery);
for (i = 0; i < count; i = i + 1 )
{
//I could not figure out the syntax for comparing to see if it was greater than or equal to percentQuery
if (strcmp (percentages[i], percentQuery) == 0)
{
printf("Here are the standings for the teams with a win percent above %i%%"), percentQuery;
printf("Team Name: %s \nLeague: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name[i], league[i], wins[i], losses[i], ties[i], percentages[i]);
}
}*/
}
//if user chooses e
else if (menu == 'e')
{
/* UNFINISHED.. COULD NOT FIGURE OUT SYNTAX
My goal was to compare my percentages array to the value that the user inputted (which was stored in the variable 'percentQuery' and display values that were less than or equal to my percent
Query
printf("In this menu, you may search for a win percentage below a certain amount.\n"
"Please enter the amount you would like to search BELOW: ");
scanf("\n%d", &percentQuery);
for (i = 0; i < count; i = i + 1 )
{
// I could not figure out the syntax for comparing to see if it was less than or equal to percentQuery
if (strcmp (percentages[i], percentQuery) == 0)
{
printf("Here are the standings for the teams with a win percent below %i%%"), percentQuery;
printf("Team Name: %s \nLeague: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name[i], league[i], wins[i], losses[i], ties[i], percentages[i]);
}
}*/
}
//Prompt user for replay of main menu
printf("\nWould you like to return to the main menu?\n"
"Enter (y)es or (n)o: ");
scanf("\n%c", &again);
}
while (again == 'y');
//whatever the user types in, strcmp to our data base and set it equal to that.
displayExit();
return 0;
}
void displayWelcome(void)
{
printf("Welcome to my Football Stats.\n\n");
}
void calcPercent(double percentages[], int count, int wins[], int losses[], int ties[])
{
int i, sum;
for (i = 0; i <= count -1; i = i + 1)
{
sum = wins[i] + losses[i] + ties[i];
percentages[i] = ((double) wins[i] / sum) * 100;
}
}
void showAll (char name[], char league[], char division[], int wins, int losses, int ties, double percentages)
{
printf("Team Name: %s \nLeague: %s\nDivision: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name, league, division, wins, losses, ties, percentages);
}
void displayExit(void)
{
printf("\nThese results were brought to you by.");
}

Just use the >= operator for "above or equal" and < for "below":
if (percentages[i] >= percentQuery) {
/* ... */
}
percentages is an array of doubles, not strings.

Related

Morra - Odds and Even

Im writing a code that evolves the computer and I entering numbers and added them together to see who wins.
There are three problems:
Problem 1: When I try to recall the 'main()' function the 'game()' wont appear.
Problem 2: I can't seem to run the code forever until user decides to stop.
Problem 3: The point system isn't accurate enough.
Any help would be grateful.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int human_fingers;
int comp_fingers;
int menu_choice;
int answer;
int count = 1;
int point1 = 0, point2 = 0;
int total;
void intro() {
printf("Welcome to Morra - Odds and Even!\n\n");
printf("The rules of the game are pretty simple\n");
printf("You and the computer will pick a side each round\n");
printf("You must enter a number and the total sum will determine the winner!\n\n");
}
void example() {
printf("You picked even, by default the computer will be odd this round\n");
printf("You entered 3 and the computer entered 5\n");
printf("3 + 5 = 8, so you win because you choose even!\n");
}
void game() {
while(count < 7)
{
count = count + 1;
printf("Enter a number to choose a side:\n");
printf("Even [1] / Odd [2]\n");
scanf("%d", &menu_choice);
while((menu_choice<1) || (menu_choice>2)){
printf("Invalid entry, please Enter 1-2: ");
scanf("%d",&menu_choice);}
if(menu_choice == 1)
{
printf("The computer will be odd this turn\n");
printf("\nPlease enter an number (1-10)\n");
scanf("%d", &human_fingers);
while((human_fingers<1) || (human_fingers>10)){
printf("Invalid entry, please enter 1-10:");
scanf("%d",&human_fingers);}
printf("Computer is choosing a number....\n");
srand(time(NULL));
comp_fingers = rand() % 10 + 1;
printf("You: %d\n", human_fingers);
printf("Computer: %d\n", comp_fingers);
int result;
result = human_fingers + comp_fingers;
printf("Total is %d\n", result);
total = result % 2;
if(total == 0)
{
printf("This turn goes to You!\n\n");
printf("You: %d\n", point1 + 1);
printf("Computer: %d\n\n", point2 + 0 );
point1++;
}
else
{
printf("This turn goes to Computer!\n\n");
printf("You: %d\n", point1 + 0 );
printf("Computer: %d\n\n", point2 + 1);
point2++;
}
}
if(menu_choice == 2)
{
printf("The computer will be even this turn\n");
printf("\nPlease enter an number (1-10)\n");
scanf("%d", &human_fingers);
while((human_fingers<1) || (human_fingers>10)){
printf("Invalid entry, please enter 1-10:");
scanf("%d",&human_fingers);}
printf("Computer is choosing a number...\n");
srand(time(NULL));
comp_fingers = rand() % 10 + 1;
printf("You: %d\n", human_fingers);
printf("Computer: %d\n", comp_fingers);
int result;
result = human_fingers + comp_fingers;
printf("Total is %d\n", result);
total = result % 1;
if(total == 0)
{
printf("This turn goes to Computer!\n\n");
printf("You: %d\n", point1 + 0);
printf("Computer: %d\n\n", point2 + 1);
point1++;
}
else
{
printf("This turn goes to You!\n\n");
printf("You: %d\n", point1 + 1);
printf("Computer: %d\n\n", point2 + 0 );
point2++;
}
}
}
if(point1 > point2)
printf("You won, you beat the computer!\n");
else
printf("Unlucky the computer won!\n");
}
void end(){
printf("Game has ended!\n");
}
int main()
{
intro();
printf("Would you like an example to demostrate?\n");
printf("Yes [1] / No [2]\n");
scanf("%d", &answer);
if( answer == 1 )
{ example();
printf("\n\n");
game();
}
else
{ printf("\n\n");
game();
}
end();
printf("Would you like play another game?\n");
printf("Yes [1] / No [2]\n");
scanf("%d", &answer);
if( answer == 1)
{
main();
}
else {
printf("Thanks for playing MORRA - ODDS AND EVEN.");
}
return 0;
}
Why not:
int main()
{
for(;;) // Infinite loop. -- equivalent of while(1) if you prefer.
{
intro();
printf("Would you like an example to demostrate?\n");
printf("Yes [1] / No [2]\n");
scanf("%d", &answer);
if( answer == 1 )
{ example();
printf("\n\n");
game();
}
else
{ printf("\n\n");
game();
}
end();
printf("Would you like play another game?\n");
printf("Yes [1] / No [2]\n");
scanf("%d", &answer);
if( answer != 1)
{
printf("Thanks for playing MORRA - ODDS AND EVEN.");
break;
//^___ exit the infinite loop.
}
}
return 0;
}
Recalling the main you should definitely not, in almost any case. Just create loops if you want to repeat everything.

cannot write/'w' FILE in function

I don't know what is wrong with this coding. I even use 'a' to output the display to for Name, Address, and Phone Number. for Read/'r' FILE my coding succefully run without any error but when try to Write FILE suddenly it cannot open the file or NULL.
This is a snapshot of the error
This is the function that I want to diplay the output in FILE of output.txt
void display(char cName[], char cAddress[], char cPhoneNo[])
{
output = fopen("output.txt", "w");
printf("\n_________________________________________________");
printf("\n_________________________________________________");
fprintf(output, "\n\n Name\t\t: %s", cName);
fprintf(output, " Address\t: %s", cAddress);
fprintf(output, " PhoneNo\t: %s", cPhoneNo);
fclose(output);
}
This is the whole coding
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void cookiesList(char[20][5], char* [], float*);
void infoInput(char[], char[], char[]);
int order(char* [], int*);
void display(char[], char[], char[]);
void outputDisplay(char[20][5], char[20][40], int[], float[], float, size_t, float, float, float, float);
float calculateSubTotal(float, int, float*);
float bundle(char*, char*, float);
FILE* input, * output;
int main()
{
char customerName[50], customerAddress[70], customerPhoneNo[12];
char productCode[20][5], productName[20][40];
int productQuantity[20], decision, orderSubTotal=0;
float productPrice[20], productPriceTotal[20];
size_t counter = 0;
float cashback, discount, finalprice;
char bundleName[10], bundleItem[32];
float bundlePrice;
printf("\t\t\t#-------------------------------------------------------#");
printf("\n\t\t\t|\t WELCOME TO ONLINE COOKIES PEOPLE STORE \t|");
printf("\n\t\t\t#-------------------------------------------------------#\n");
infoInput(customerName, customerAddress, customerPhoneNo);
do
{
decision = order(&productCode[counter], &productQuantity[counter]);
cookiesList(productCode[counter], &productName[counter], &productPrice[counter]);
orderSubTotal = orderSubTotal + calculateSubTotal(productPrice[counter], productQuantity[counter], &productPriceTotal[counter]);
counter++;
} while (decision == 1);
bundlePrice = bundle(&bundleName, &bundleItem, orderSubTotal);
if ((15 <= orderSubTotal) && (orderSubTotal < 76))
{
cashback = 1.5;
discount = 0;
}
else if ((76 <= orderSubTotal) && (orderSubTotal < 151))
{
cashback = 2.5;
discount = orderSubTotal * 0.05;
}
else if (151 <= orderSubTotal)
{
cashback = 3.5;
discount = orderSubTotal * 0.1;
}
finalprice = orderSubTotal - discount + bundlePrice;
display(customerName, customerAddress, customerPhoneNo);
outputDisplay(productCode, productName, productQuantity, productPriceTotal, orderSubTotal, counter
, discount, cashback, finalprice, bundlePrice);
return 0;
}
void cookiesList(char pdtCode[][5], char* pdtNm[], float* pdtprice)
{
if ((strcmp(pdtCode, "c111") == 0) || (strcmp(pdtCode, "C111") == 0))
{
strcpy(pdtNm, "Dark Chocolate Chips");
*pdtprice = 15.0;
}
else if ((strcmp(pdtCode, "c112") == 0) || (strcmp(pdtCode, "C112") == 0))
{
strcpy(pdtNm, "Premium Assorted Shortbread Cookies");
*pdtprice = 25.5;
}
else if ((strcmp(pdtCode, "c113") == 0) || (strcmp(pdtCode, "C113") == 0))
{
strcpy(pdtNm, "Hawaiian Salted Coconut");
*pdtprice = 17.5;
}
else if ((strcmp(pdtCode, "c114") == 0) || (strcmp(pdtCode, "C114") == 0))
{
strcpy(pdtNm, "Oatmeal & Raisins Cookies");
*pdtprice = 13.0;
}
else if ((strcmp(pdtCode, "c115") == 0) || (strcmp(pdtCode, "C115") == 0))
{
strcpy(pdtNm, "Chocolate Caramel Almond Cookies");
*pdtprice = 16.0;
}
else
{
exit(cookiesList);
}
}
void infoInput(char cNm[], char cAdrs[], char cPhN[])
{
input = fopen("file.txt", "r");
if (input == NULL) {
printf("ERROR! File does not have any input");
return(-1);
}
else {
//fgets(cNm, 50, fp);
fscanf(input, "\n%[^\n]%*c", cNm);
printf("\n Name entered\t\t: %s", cNm);
//fgets(cAdrs, 70, fp);
fscanf(input, "\n%[^\n]%*c", cAdrs);
printf("\n Address entered\t: %s", cAdrs);
//fgets(cPhN, 12, fp);
fscanf(input, "\n%[^\n]%*c", cPhN);
printf("\n Phone No. entered\t: %s", cPhN);
printf("\n ----------------Product-------------------");
printf("\n C111: Dark Chocolate Chips");
printf("\n C112: Premium Assorted Shortbread Cookies");
printf("\n C113: Hawaiian Salted Coconut");
printf("\n C114: Oatmeal & Raisins Cookies");
printf("\n C115: Chocolate Caramel Almond Cookies");
printf("\n ------------------------------------------\n");
}
fclose(input);
}
int order(char* pdtCdLt[], int* pdtQtyLt)
{
int YorN;
printf(" Enter Product Code\t: ");
scanf(" %s", pdtCdLt);
printf(" Enter Quantity\t\t: ");
scanf(" %d", pdtQtyLt);
printf(" Want to add other product?( Yes = 1 | No = 0 ) ");
scanf(" %d", &YorN);
return YorN;
}
void display(char cName[], char cAddress[], char cPhoneNo[])
{
output = fopen("output.txt", "w");
printf("\n_________________________________________________");
printf("\n_________________________________________________");
fprintf(output, "\n\n Name\t\t: %s", cName);
fprintf(output, " Address\t: %s", cAddress);
fprintf(output, " PhoneNo\t: %s", cPhoneNo);
fclose(output);
}
void outputDisplay(char pdtCd[][5], char pdtName[][40], int pdtQty[], float pdtPriceTtl[], float odrSubTotal, size_t index
, float disc, float CashB, float Fprice, float bdlPri)
{
//yolo = fopen("output.txt", "w");
/*if (yolo == NULL) {
printf("Could Not open file!");
return 0;
}*/
printf("\n Item\t\tQuantity\t\tPrice(RM)\n");
for (size_t i = 0; i < index; i++)
{
printf("\n %s", pdtName[i]);
printf("\n %s\t\t%d\t\t\t%.2f", pdtCd[i], pdtQty[i], pdtPriceTtl[i]);
}
printf("\n\n\t\t\t\t\t============");
printf("\n\t\t\t Subtotal\t%.2f", odrSubTotal);
if (bdlPri > 0)
{
printf("\n\t\t Bundle Price\t%.2f", bdlPri);
}
if (disc > 0)
{
printf("\n\t\t\t Discount\t%.2f", disc);
}
printf("\n\t\t\t CashBack\t%.2f", CashB);
printf("\n\t\t\tFinal price\t%.2f\n", Fprice);
//fclose(yolo);
}
float calculateSubTotal(float pdtPri, int pdtQuanti, float* pdtPTtl)
{
float subTtl;
*pdtPTtl = pdtPri * ((float)pdtQuanti);
return *pdtPTtl;
}
float bundle(char* bdlNm, char* bdlItm, float odrSubTtl)
{
int yorn;
float bdlPrice;
printf("\n Do you want to choose any bundle?");
printf("\n *Every bundle is RM 5 each.( Yes = 1 | No = 0 ) ");
scanf(" %d", &yorn);
if (yorn == 1)
{
printf("\n\t#-----------------------------Type of Bundle----------------------------#");
printf("\n\t|\t\t\t|\t\t\t|\t\t\t|");
printf("\n\t|\t Bundle A \t|\t Bundle B \t|\t Bundle C \t|");
printf("\n\t|\tRecycle Bag\t|\tRecycle Bag\t|\tRecycle Bag\t|");
printf("\n\t|\t & \t|\t & \t|\t & \t|");
printf("\n\t|\t NoteBook \t|\tWater Bottle\t|\tMark Cup\t|");
printf("\n\t|_______________________|_______________________|_______________________|\n");
retry:
printf("\n A = Bundle A, B = Bundle B, C = Bundle C ");
printf("\n Choose Your wanted Bundle : ");
fflush(stdin);
scanf(" %c", &(*bdlNm));
if ((*bdlNm == 'a') || (*bdlNm == 'A'))
{
strcpy(bdlItm, "Recycle bag and Notebook");
}
else if ((*bdlNm == 'b') || (*bdlNm == 'B'))
{
strcpy(bdlItm, "Recycle Bag and Water Bottle");
}
else if ((*bdlNm == 'c') || (*bdlNm == 'C'))
{
strcpy(bdlItm, "Recycle bag and Mark Cup");
}
else
{
printf("\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#");
printf("\n{\t\t\t\t}");
printf("\n }---------ERROR INPUT---------{");
printf("\n{\t\t\t\t}");
printf("\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#");
}
bdlPrice = 5;
}
else
{
bdlPrice = 0;
}
return bdlPrice;
}
What are your OS and IDE?
I think that you are using Windows & VS now.
If you are running this program in Windows, Please start IDE with "Run as Administrator" like below.

Unresolved external symbol in c for user-define function

im very new to programming and for my course we learning c language so have mercy on my badly written code and the compiler just wont run the program because of the error so its hard for me to identify whats wrong.Back to main question im getting unresolved external symbol...referenced in function_main and i dont really know where im messed up
#include<stdio.h>
char DisplayMenu(void);
void ViewBooks();
void SearchBookPrice();
void UpdateBookPrice();
int main()
{
char userchoice;
int bookID[5] = { 200,230,500,540,700 };
char bookTitle[5][50] = { {"Using Information Technology 12th Edition" }, { "Beyond HTML" },{"Build Your Own PC"},{"Instant Java Servlets"},{"DIgital Image: A Practical Guide"} };
float bookPrice[5] = { 100.30,50.40,47,83.30,22.90 };
do
{
userchoice = DisplayMenu();
if (userchoice == 'V')
ViewBooks();
else if (userchoice == 'S')
SearchBookPrice();
else if (userchoice == 'U')
UpdateBookPrice();
} while (userchoice != 'E');
printf("Thank you for using our system. Have a nice day!\n");
return 0;
}
char DisplayMenu(void)
{
char choice;
printf("*************************************************************************\n");
printf("V:View Books S:Search Book Price U:Update Book Price E:Exit");
printf("*************************************************************************\n");
do
{
printf("Enter your choice: ");
scanf(" %c", &choice);
if (choice != 'V' && choice != 'S' && choice != 'U' && choice != 'E')
printf("Invalid Choice\n");
} while (choice != 'V' && choice != 'S' && choice != 'U' && choice != 'E');
return choice;
}
void ViewBooks(int bookID[],float bookPrice[])
{
printf("%d Using Information Technology 12th Edition $%f\n", bookID[0], bookPrice[0]);
printf("%d Beyond HTML $%f\n", bookID[1], bookPrice[1]);
printf("%d Build Your Own PC $%f\n", bookID[2], bookPrice[2]);
printf("%d Instant Java Servlets $%f\n", bookID[3], bookPrice[3]);
printf("%d Digital Image: A Pratical Guide $%f\n", bookID[4], bookPrice[4]);
return;
}
void SearchBookPrice(int bookID[5],char bookTitle[5][50], float bookPrice[5])
{
int idsearch, i= 0, match = -1;
printf("*************************************************************************\n");
printf("Search by book ID\n");
printf("*************************************************************************\n");
printf("Enter book ID: ");
scanf("%d", &idsearch);
while (i<5 && match==-1)
{
if (bookID[i] == idsearch)
match = i;
i++;
}
if (match == -1)
printf("Please refer to the customer service for assitance");
else
{
printf("The book id is : %d\n", &idsearch);
printf("The price of %s is %f", bookTitle[match], bookPrice[match]);
}
return;
}
void UpdateBookPrice(int bookID[5], char bookTitle[5][50], float bookPrice[5])
{
int idsearch, i = 0, match = -1;
printf("Enter book ID: ");
scanf("%d", &idsearch);
while (i < 5 && match == -1)
{
if (bookID[i] == idsearch)
match = i;
i++;
}
if (match == -1)
printf("The book ID is not found. Please make sure the book ID is correct");
else
{
printf("Current book price is %f\n", bookPrice[match]);
printf("Enter new price for (%d-%s): ", bookID[match], bookTitle[match]);
scanf("%f", &bookPrice[match]);
}
return;
}
Your function declaration is not matched with function body.
This is working code.
#include<stdio.h>
char DisplayMenu(void);
void ViewBooks(int bookID[],float bookPrice[]);
void SearchBookPrice(int bookID[5],char bookTitle[5][50], float bookPrice[5]);
void UpdateBookPrice(int bookID[5], char bookTitle[5][50], float bookPrice[5]);
int main()
{
char userchoice;
int bookID[5] = { 200,230,500,540,700 };
char bookTitle[5][50] = { {"Using Information Technology 12th Edition" }, { "Beyond HTML" },{"Build Your Own PC"},{"Instant Java Servlets"},{"DIgital Image: A Practical Guide"} };
float bookPrice[5] = { 100.30,50.40,47,83.30,22.90 };
do
{
userchoice = DisplayMenu();
if (userchoice == 'V')
ViewBooks(bookID, bookPrice);
else if (userchoice == 'S')
SearchBookPrice(bookID, bookTitle, bookPrice);
else if (userchoice == 'U')
UpdateBookPrice(bookID, bookTitle, bookPrice);
} while (userchoice != 'E');
printf("Thank you for using our system. Have a nice day!\n");
return 0;
}
char DisplayMenu(void)
{
char choice;
printf("*************************************************************************\n");
printf("V:View Books S:Search Book Price U:Update Book Price E:Exit");
printf("*************************************************************************\n");
do
{
printf("Enter your choice: ");
scanf(" %c", &choice);
if (choice != 'V' && choice != 'S' && choice != 'U' && choice != 'E')
printf("Invalid Choice\n");
} while (choice != 'V' && choice != 'S' && choice != 'U' && choice != 'E');
return choice;
}
void ViewBooks(int bookID[],float bookPrice[])
{
printf("%d Using Information Technology 12th Edition $%f\n", bookID[0], bookPrice[0]);
printf("%d Beyond HTML $%f\n", bookID[1], bookPrice[1]);
printf("%d Build Your Own PC $%f\n", bookID[2], bookPrice[2]);
printf("%d Instant Java Servlets $%f\n", bookID[3], bookPrice[3]);
printf("%d Digital Image: A Pratical Guide $%f\n", bookID[4], bookPrice[4]);
return;
}
void SearchBookPrice(int bookID[5],char bookTitle[5][50], float bookPrice[5])
{
int idsearch, i= 0, match = -1;
printf("*************************************************************************\n");
printf("Search by book ID\n");
printf("*************************************************************************\n");
printf("Enter book ID: ");
scanf("%d", &idsearch);
while (i<5 && match==-1)
{
if (bookID[i] == idsearch)
match = i;
i++;
}
if (match == -1)
printf("Please refer to the customer service for assitance");
else
{
printf("The book id is : %d\n", &idsearch);
printf("The price of %s is %f", bookTitle[match], bookPrice[match]);
}
return;
}
void UpdateBookPrice(int bookID[5], char bookTitle[5][50], float bookPrice[5])
{
int idsearch, i = 0, match = -1;
printf("Enter book ID: ");
scanf("%d", &idsearch);
while (i < 5 && match == -1)
{
if (bookID[i] == idsearch)
match = i;
i++;
}
if (match == -1)
printf("The book ID is not found. Please make sure the book ID is correct");
else
{
printf("Current book price is %f\n", bookPrice[match]);
printf("Enter new price for (%d-%s): ", bookID[match], bookTitle[match]);
scanf("%f", &bookPrice[match]);
}
return;
}

Why does this program crash when I run through the loop a 2nd time?

Try as I might to solve this riddle, I think I'm losing my mind! Can anyone help understand why this program crashes when I run through the loop a 2nd time?
I can run through the interactive loop one time and have the values entered written to a file. However, when I attempt to pass through the a loop a 2nd time, the program chokes.
// C Libraries Used
#include <stdio.h>
#include <math.h>
#include <string.h>
// Constant definitions
const float OTPAYFACTOR = 1.5;
const float REGWORKWKHRS = 40;
FILE *payfile; // report file (for output)
// Variable declerations
char deptname [21];
char firstname [10];
char lastname [10];
char fullname [47];
float hrsworked;
float hrwage;
float reghrsworked;
float othrsworked;
float otwage;
float grosswage;
int count;
char again;
// Function Prototypes
//**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~
// M A I N F U N C T I O N
//**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~
int main (void){
payfile = fopen("c:\\class\\mod6\\ethan-pay.txt","w"); // Open disk file
printf("Mountain Pacific Corporation\nDepartment Salary Program\n\n");
printf("Please enter the name of the department: ");
scanf("%s", deptname);
count = 0; // Initialize this "counting" variable to zero to start
printf("%s", deptname);
printf("\n");
do {
printf("Enter employee #%d: ", count+1);
scanf("%s %s", firstname, lastname);
fscanf(payfile,"%s %s", firstname, lastname);
strcpy(fullname, firstname);
strcat(fullname, " ");
strcat(fullname, lastname);
printf("Enter the hourly wage of %s: ", fullname);
scanf("%f", &hrwage);
fscanf(payfile,"%f", &hrwage);
printf("Enter total number of hours: ");
scanf("%f", &hrsworked);
fscanf(payfile,"%f", &hrsworked);
if (hrsworked <= REGWORKWKHRS){ //
reghrsworked = hrsworked;
othrsworked = 0;
otwage = hrwage * OTPAYFACTOR;
grosswage = hrwage*reghrsworked;
}
else{
reghrsworked = REGWORKWKHRS;
othrsworked = hrsworked - REGWORKWKHRS;
otwage = hrwage * OTPAYFACTOR;
grosswage = (reghrsworked * hrwage) + (othrsworked * otwage);
}
fprintf(payfile,"%-22s%0.1f ($%0.2f) %6.1f ($%0.2f) $%-4.2f\n", fullname, reghrsworked, hrwage, othrsworked, otwage, grosswage);
printf("\nThank you. Process another employee? ");
scanf ("%s", &again);
printf("\n");
count++; // Increment the counting variable
} while (again == 'Y'|| again == 'y' || again != 'N' && again != 'n');
printf("End of processing.\n");
fclose(payfile);
return 0;
}
I don't understand why are you scanning your file that you use for save the result:
scanf("%s %s", firstname, lastname);
fscanf(payfile,"%s %s", firstname, lastname);
// ...
scanf("%f", &hrwage);
fscanf(payfile,"%f", &hrwage);
// ...
scanf("%f", &hrsworked);
fscanf(payfile,"%f", &hrsworked);
What you do erase previous value. Just remove all call to fscanf().
I strongly advice you to change your code practice, global should be avoid, only declare variable when you need them, don't ignore error code from function, provide to scanf() the max size that it can use, etc...
example probably not perfect:
#include <stdio.h>
#include <string.h>
#define OTPAYFACTOR 1.5
#define REGWORKWKHRS 40
int main(void) {
printf("Mountain Pacific Corporation\nDepartment Salary Program\n\n"
"Please enter the name of the department: ");
char deptname[21];
if (scanf("%20s", deptname) != 1) {
return 1;
}
printf("%s\n", deptname);
FILE *payfile = fopen("c:\\class\\mod6\\ethan-pay.txt", "w");
if (!payfile) {
return 1;
}
for (int count = 0;; count++) {
printf("Enter employee #%d: ", count + 1);
char firstname[10];
char lastname[10];
if (scanf("%9s %9s", firstname, lastname) != 2) {
return 1;
}
char fullname[19];
sprintf(fullname, "%s %s", firstname, lastname);
printf("Enter the hourly wage of %s: ", fullname);
float hrwage;
if (scanf("%f", &hrwage) != 1) {
return 1;
}
printf("Enter total number of hours: ");
float hrsworked;
if (scanf("%f", &hrsworked) != 1) {
return 1;
}
if (hrsworked <= REGWORKWKHRS) {
float reghrsworked = hrsworked;
float othrsworked = 0;
float otwage = hrwage * OTPAYFACTOR;
float grosswage = hrwage * reghrsworked;
fprintf(stdout, "%-22s%0.1f ($%0.2f) %6.1f ($%0.2f) $%-4.2f\n", fullname,
reghrsworked, hrwage, othrsworked, otwage, grosswage);
} else {
float reghrsworked = REGWORKWKHRS;
float othrsworked = hrsworked - REGWORKWKHRS;
float otwage = hrwage * OTPAYFACTOR;
float grosswage = (reghrsworked * hrwage) + (othrsworked * otwage);
fprintf(stdout, "%-22s%0.1f ($%0.2f) %6.1f ($%0.2f) $%-4.2f\n", fullname,
reghrsworked, hrwage, othrsworked, otwage, grosswage);
}
printf("\nThank you. Process another employee? ");
char again;
if (scanf(" %c", &again) != 1) {
return 1;
}
if (again != 'Y' && again != 'y') {
break;
}
printf("\n");
}
fclose(payfile);
printf("End of processing.\n");
}
example input:
jurasickpark
sarah connor 5 42
y
bob lennon 9 12
n
output file:
sarah connor 40.0 ($5.00) 2.0 ($7.50) $215.00
bob lennon 12.0 ($9.00) 0.0 ($13.50) $108.00

c programming language : the app wont stop after typing x

i made this program and its working just how i want but it should stop when i type x but it doesn't
can any one tell me why?
and if there is any shortcut or smaller way to type this code?
thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int meat[6];
int i;
int total =0;
int avg;
char what[20];
char end;
int days = 0;
char food[20];
char drink[20];
printf("what thing do u want to calculate the average of?(food/drink)\n");
scanf(" %s", &what);
if(strcmp(what, "food")==0)
{
printf("what sort of food did u ate ?\n");
scanf(" %s", food);
}
if(strcmp(what, "drink")==0)
{
printf("what sort of drink did u drank ?\n");
scanf(" %s", drink);
}
for(i=0; i<6; i++)
{
days++;
if(strcmp(what, "food")==0)
{
printf("how many %s did u ate in day %d\n", food, i+1);
}
else if(strcmp(what, "drink")==0)
{
printf("how many liters of %s did u drank in day %d\n", drink, i+1);
}
scanf(" %d", &meat[i]);
total += meat[i];
printf("if u want to continue type y\n");
printf("type x if u want to finish\n");
scanf(" %c", &end);
if((end = 'y')&&(i<5))
{
continue;
}
else if(end = 'x' && strcmp(what, "drink")==0)
{
avg = total / days;
printf("\nyour average amount of liters of %s you had %d\t the total is %d\n", drink, avg, total);
}
else if(end = 'x' && strcmp(what, "food")==0)
{
avg = total / days;
printf("\nyour average amount of %s you had %d\t the total is %d\n", food, avg, total);
}
break;
}
if(strcmp(what, food)==0)
{
printf("\nyour average amount of %s you had is %d\t the total is %d\n", food, avg, total);
}
else if(strcmp(what, drink)==0)
{
printf("\nyour average amount of liters of %s you had is %d\t the total is %d\n", drink, avg, total);
}
return 0;
}
else if(end = 'x' ...
should be:
else if(end == 'x' ...
You use == to test equality in if statements. You've got this in a couple places in your code, which is inadvertently performing an assignment, not what you want to achieve by comparing if user input is equal to a particular character.
Replace the = with == here:
else if(end = 'x' && strcmp(what, "drink")==0)
here:
else if(end = 'x' && strcmp(what, "food")==0)
and here:
if((end = 'y')&&(i<5))

Resources