I am trying to make a program in the C language that can take in employee information in array struct (not parallel) form and output it into a text file.
The program will compare the job code and calculate the commission rate of the employee.
I have 2 questions:
1 - the commission of the salesPerson is always 0 even when I enter one of TEL, SAL, SSR. Is it a problem with my string comparison?
2 - how do I output my results into a text file (inside the project folder)?
Edit - I have figured out how to print my file into a txt. Thank you all for your help!
#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
//job codes
char TEL[4] = "TEL";
char SAL[4] = "SAL";
char SSR[4] = "SSR";
//create a sales person structure
struct salesPerson
{
char name[31];
int salesID;
char jobCode[4];
double totalSales;
double commission;
}e[10]; //make an array of 10 employees
int _tmain(int argc, _TCHAR* argv[])
{
//get employee info
for(int i=0; i<3; i++)
{
printf("\nEnter the sales person's name: ");
scanf(" %s", &e[i].name);
printf("\nEnter the sales person's ID: \n");
scanf(" %d%*c", &e[i].salesID);
printf("\nEnter the sales person's job code: \n");
scanf(" %s", &e[i].jobCode);
printf("\nEnter the total sales of the sales person: ");
scanf(" %lf", &e[i].totalSales);
//determine commission based on jobCode
if(strcmp(e[i].jobCode, TEL) == 0)
{
e[i].commission = e[i].totalSales*0.02;
}
if(strcmp(e[i].jobCode, SAL) == 0)
{
e[i].commission = e[i].totalSales*0.05;
}
if(strcmp(e[i].jobCode, SSR) == 0)
{
e[i].commission = e[i].totalSales*0.07;
}
else
{
printf("\n----------");
}
}
printf("\n%d\n", e[0].commission);
printf("\n%d\n", e[1].commission);
printf("\n%d\n", e[2].commission);
//print stuff to txt file
FILE *fpOut, *fpIn;
/*
if ((fpIn = fopen("c:\\temp\\salesEmployees.txt", "w")) == NULL)
{
printf("Error opening the file for processing\n\n");
}
else
{
fpOut = fopen("c:\\temp\\salesEmployees.txt", "w");
for(int i=0; i<3; i++)
{
//fscanf(fpIn,"%[^\n]", &e[i].name);
//fscanf(fpIn,"%f%*c", &e[i].salesID);
fprintf(fpOut, "\nName: %s", e[i].name);
fprintf(fpOut, "\nSalesID: %d*c ", e[i].salesID);
fprintf(fpOut, "\nJob code: %s ", e[i].jobCode);
fprintf(fpOut, "\nTotal sales: %.2lf", e[i].totalSales);
fprintf(fpOut, "\nCommission earned: %.2lf", e[i].commission);
fprintf(fpOut, "\n\n");
}
//fclose(fpOut);
}*/
}
To answer the second part of your question (about program crashing, and keeping file in same directory): you open the same file for input and output without closing in between; not sure why the input is even there. Assuming (for simplicity) that you only want to save to file what was entered from the keyboard, you can just remove all reference to the fpIn. As for the "keep file in same folder" - just use a relative path. When you run from c:\my\dir, then opening a file salesOutput.txt will cause it to be written to c:\my\dir\salesOutput.txt.
Complete and working code (some changes to accommodate my compiler settings...):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//job codes
char TEL[4] = "TEL";
char SAL[4] = "SAL";
char SSR[4] = "SSR";
//create a sales person structure
struct salesPerson
{
char name[31];
int salesID;
char jobCode[4];
double totalSales;
double commission;
}e[10]; //make an array of 10 employees
int main(int argc, char* argv[])
{
//get employee info
int i;
for(i=0; i<3; i++)
{
printf("\nEnter the sales person's name: ");
scanf(" %s", &e[i].name);
printf("\nEnter the sales person's ID: \n");
scanf(" %d%*c", &e[i].salesID);
printf("\nEnter the sales person's job code: \n");
scanf(" %s", &e[i].jobCode);
printf("\nEnter the total sales of the sales person: ");
scanf(" %lf", &e[i].totalSales);
//determine commission based on jobCode
if(strcmp(e[i].jobCode, TEL) == 0)
{
e[i].commission = e[i].totalSales*0.02;
}
if(strcmp(e[i].jobCode, SAL) == 0)
{
e[i].commission = e[i].totalSales*0.05;
}
if(strcmp(e[i].jobCode, SSR) == 0)
{
e[i].commission = e[i].totalSales*0.07;
}
else
{
printf("\n----------");
}
}
printf("\n%lf\n", e[0].commission);
printf("\n%lf\n", e[1].commission);
printf("\n%lf\n", e[2].commission);
//print stuff to txt file
FILE *fpOut;
{
if((fpOut = fopen("salesEmployees.txt", "w")) == NULL)
{
printf("Unable to open file - quitting\n");
return -1;
};
int i;
for(i=0; i<3; i++)
{
fprintf(fpOut, "\nName: %s", e[i].name);
fprintf(fpOut, "\nSalesID: %d*c ", e[i].salesID);
fprintf(fpOut, "\nJob code: %s ", e[i].jobCode);
fprintf(fpOut, "\nTotal sales: %.2lf", e[i].totalSales);
fprintf(fpOut, "\nCommission earned: %.2lf", e[i].commission);
fprintf(fpOut, "\n\n");
}
fclose(fpOut);
}
}
Obviously it is desirable (and necessary) to add addition I/O, error checking on inputs, etc - but this should get you past the point of "it's not working and I don't know why". I did wonder why you have the *c in the printout of the sales ID - it just gets added to the output - but I decided not to remove it.
Good luck with the coding!
Always look at the warnings from your compiler. You have
printf("\n%d\n", e[0].commission);
Where you give an integer format specifier, but the argument is double. The first few bytes of that may well be zero - which is why the result prints as zero. Try changing it to:
printf("\n%.2lf\n", e[0].commission);
And you will get the commission in dollars and cents. Same for the other lines.
Related
I have this task/function to determine if student's name/complete name already exist in the record.
No student's name should be the same in every input/entry. also no duplicate of entry in record.
The Error of my code:
Is that when I input 5 student names (e.g : A,B,C,D,E) then and search for D the return value will be not found. So I wonder what would be the correct logic for it to search every element if it exist? And when I tried A it says "Already Exist".
#include<stdio.h>
#include<string.h>
int main(){
char studentNames[50][50],names[50][50];
int i,studentcount;
printf("\nEnter number of students: ");
scanf("%d",&studentcount);
for(int i=0; i<studentcount; i++){
printf("\n[Student %d of %d]\n",i+1,studentcount);
printf("Enter name of student %d: \n",i+1);
scanf("%s", studentNames[i]);
}//this is the student record initialize.
/*assumed this is a function where it holds the data name to be searched
e.g
names[i]= "spiderman" then in studentNames[i]="venom",studentNames[i]="harley",studentNames[i]="octopops",
if i loop will it function like this?
the names[i]=spiderman compare to studentnames[i]=venom then if not equal iterate to harley and so on.
That's what I really want to do with my searching but I really dont know how to do it because of my poor logic thinking.
*/
for(int i=0; i<studentcount; i++){
printf("\nEnter Student's Name to be search: ");
scanf("%s",names[i]);
if (strcmp(studentNames[i],names[i]) == 0)
{
printf("Already exist.\n");
return 0;
}
printf("Not found\n");
return 1;
}
}
You probably want something like this:
char CompareStudent() {
printf("\nEnter Student's Name to be search: ");
char searchedname[100];
scanf("%99s", searchedname); // %99s instead of %s prevents buffer overflow
// (not very important at your level)
for (int i = 0; i < studentCount; i++) {
if (strcmp(studentNames[i], searchedname) == 0) {
printf("Already exists.\n");
return 0;
}
}
printf("Not found\n");
return 1;
}
This is your original bogous code with comments:
char CompareStudent() {
printf("\nEnter Student's Name to be search: ");
for (int i = 0; i < studentCount; i++) {
scanf("%s", names[i]); // 1
if (strcmp(studentNames[i], names[i]) == 0)
{
printf("Already exist.\n");
return 0;
}
printf("Not found\n"); // 2
return 1;
}
}
Problems:
You need to ask to input the student to search only once, not each time in the loop
This part must be outside the loop. In your code, we return inconditionally 1 if the student is not in the first element of the array.
I'm reading a book called "C programming Absolute Beginners Guide."
The following program uses some if loops and strcpy to store some character arrays provided by the user. The first pass of strcpy works fine. The second produces garbage. I understand the array needs a \0 to end. According to the book, strcpy does this automatically. What am I missing?
#include <stdio.h>
#include <string.h>
main()
{
int ctr, numMovies, rating, favRating, leastRating;
char movieName[40], favorite[40], least[40];
favRating = 0;
leastRating = 0;
do {
printf("How many movies have you seen this year? ");
scanf(" %d", &numMovies);
if (numMovies < 1)
{
printf("No movies! How can you rank them?\nTry again\n\n");
}
} while (numMovies < 1 );
for (ctr = 1; ctr <= numMovies; ctr++)
{
printf("\nWhat's the name of the movie? ");
printf("(1-word titles only!) ");
scanf(" %s", movieName);
printf("On a scale of 1 to 10, what would ");
printf("you rate it? ");
scanf(" %d", &rating);
if (rating > favRating)
{
strcpy(favorite, movieName);
favRating = rating;
}
printf("%s", movieName);
if (rating < leastRating)
{
strcpy(least, movieName);
leastRating = rating;
}
}
printf("\nYour Favorite Movie was %s.\n", favorite);
printf("\nYour Least-favorite movie was %s.\n", least);
return 0;
}
Because you initialize leastRating to zero you won't have a least favorite unless the rating is negative. Not sure that's what you want.
The best suggestion is from #xing, add a include
#include <limits.h>
and initialize you best and worst like this;
favRating = INT_MIN;
leastRating = INT_MAX;
I am trying to store data for Value, Weight and Cost from a file containing a table which contains three columns of numbers for Value, Weight and Cost. The table may vary in length (9 or 21 rows) depending on the file chosen by the user.
I am having trouble trying to store the data from this file to use in a brute force function to solve the problem.
This is what I have so far.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int nr_rows;
int i = 1;
int j = 2;
int k = 3;
int l,m,n = 0;
int budget_cost;
int weight_lim;
char file_name[50];
float c[nr_rows][3];
char stringA[20] = "objectsA.txt";
char stringB[20] = "objectsB.txt";
printf("Enter the filename containing item listing: ");
scanf("%s", &file_name);
if(strcmp(file_name,stringA)==0)
{
nr_rows = 9;
}
else if(strcmp(file_name,stringB)==0)
{
nr_rows = 21;
}
printf("The number of rows is %d", nr_rows);
float value[nr_rows], weight[nr_rows], price[nr_rows];
FILE *fpointer;
fpointer = fopen(file_name, "r");
if(!fpointer)
{
printf("The file %s could not be opened.", file_name);
return 1;
}
j=0;
while(j<nr_rows)
{
i=0; // Skip the first line
while(i<3)
{
fscanf(fpointer, "%f", &c[j][i]);
//printf("%.0f\n", c[j][i]);
if(i=1) /* Change this if statement so that 1 ,4 ,7 ,10
etc. activates*/
{
c[j][i] = v[l];
l++;
printf("%f", v[l]);
}
else if(i=2)/* Change this if statement so that 2,5,8 etc.
activates*/
{
c[j][i] = w[m];
m++;
}
else if(i=3)/* Change this if statement so that 3,6,9 etc.
activates*/
{
c[j][i] = p[n];
n++;
}
i++;
}
j++;
}
fclose(fpointer);
//1. Read carefully your file name by doing:
scanf("%s", file_name); // instead of scanf("%s", &file_name);
//2. Declare c[nr_rows][3] only after reading "nr_rows"
//3. The main "while" loop could look like this
while(j < nr_rows)
{
fscanf(fpointer, "%f %f %f", &c[j][0], &c[j][1], &c[j][2]);
}
// Then,
fclose(fpointer);
I've been working on this school assignment which creates a restaurant menu, and I have an array to store everything that a person orders. The array that stores the orders ordered is array OrderedItems [30]. This array is basically a counter. When a person orders order number 1 as an example OrderItems[1] increases by 1.
I've tried to initialize by using OrderedItems [30] = {0}, and using a for loop to initialize every spot individually, However, that didn't work. Please help me initialize this array. I've also tried memset(OrderedItems, 0, 30); and this didn't work too so I really have no clue what to do.
I also want to add that I've tried to globally declare the OrderedItems array since I've heard that all global declarations are automatically initialized to 0, but that also didn't work.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <windows.h>
FILE *fPointer1; //for food//
FILE *fPointer2; //for invoice//
int count;
char name[50];
float price;
void FunctionToPrintFoodItems (void)
{
fPointer1 = fopen ("Food.txt", "a+");
float price;
printf("ITEMCODE\tDESCIPTION\tPRICE (RM)\n");
while (!feof (fPointer1))
{
fscanf(fPointer1, "%d %s %f", &count, name, &price);
printf("%d\t\t%s\t\t%.2f\n", count, name, price);
}
fclose (fPointer1);
}
void clrscr()
{
system("#cls||clear"); //might not need. Will delete it not needed//
}
void debug (void)
{
printf("THIS IS PRINTED");
}
#define clear clrscr ();
#define printfood FunctionToPrintFoodItems();
#define de debug();
int main ()
{
fPointer1 = fopen("Food.txt", "w");
fprintf(fPointer1, "1 BigM 10.40\n");
fprintf(fPointer1, "2 Cheeseburger 9.45");
fclose (fPointer1);
int i;
int MainMenuCode;
int additems = 0;
int orderitems;
int item;
int ordered;
int OrderedItems[30] = {0};
memset(OrderedItems, 0, 30);
for (i=0 ; i < 30 ; i++)
{
OrderedItems[i] = NULL;
printf("%d: %d\n", i, OrderedItems);
}
do
{
printf("WELCOME TO RESTOURANT MAC C - Main Menu\n\n");
printf("[1] Add new food items\n\n");
printf("[2] Take order\n\n");
printf("Enter ITEM CODE (0 to Quit) : ");
scanf("%d", &MainMenuCode);
if (MainMenuCode == 1)
{
clear;
additems = 1;
printf("WELCOME TO RESTAURANT MAC C - Add Menu\n\n");
printfood;
printf("\n");
while ( additems == 1 )
{
printf("Enter description (0 to Main Menu) : ");
scanf("%s", name);
if (strcmp (name, "0") == 0)
{
additems = 0;
clear;
break;
}
printf("Enter price (RM) : ");
scanf("%f", &price);
count ++;
fPointer1 = fopen ("Food.txt", "a");
printf("\n%d\t\t%s\t\t%.2f\n\n", count, name, price);
fprintf(fPointer1, "\n%d %s %.2f", count, name, price);
fclose (fPointer1);
}
}
else if (MainMenuCode == 2)
{
clear;
orderitems = 1;
printf("WELCOME TO RESTAURANT MAC C- Take Order\n\n");
printfood;
while (orderitems == 1)
{
fPointer1 = fopen ("Food.txt", "a+");
printf("Enter ITEM CODE (0 to Quit, 100 for Main Menu) : ");
scanf("%d", &item);
if (item == 100) break;
else if (item == 0) //final approach//
{
fPointer2 = fopen ("Invoice.txt", "a+");
de;
fclose (fPointer2);
return 0;
}
else if (item == 900)
{
for (i=0 ; i < 30 ; i++)
printf("%d: %d\n", i, OrderedItems);
}
else if (item > count || item < 1)
{
printf("\n\nITEM CODE not available. Try again\n\n");
}
else
{
OrderedItems[item]++;
printf("%d %d", item, OrderedItems);
}
fclose (fPointer1);
}
}
else printf("Please enter a valid Menu Code\n");
} while (MainMenuCode != 0);
return 0;
}
- printf("%d: %d\n", i, OrderedItems);
+ printf("%d: %d\n", i, OrderedItems[i]);
OrderedItems is an address of the array's first element.
OrderedItems[0] is a value of the array's first element.
OrderedItems[i] is a value of the array's i-th element.
The call to memset should specify how many bytes to set. You need to tell it the size of the type to initialise.
memset(OrderedItems, 0, 30 * sizeof(int))
I have been trying to figure out why my code isn't working properly. I know my code below is a mess (I am a rather poor C programmer thus far). Its a work in progress. Specifically
printf("Please enter the index of the contact you wish to view. \nThis should be a positive integer\n\n");
scanf("%d", &vIndex);
fgetc(stdin);
printf("The value of vIndex is %d", &vIndex);
I find that when i run my program I might select a keyboard input of 1, meaning I am looking at my second record in my file entries.txt. The printout of vIndex however is a number much much larger, much likely the last information stored there. Running in debug however, i find that vIndex change to 1 and but prints the strange number. My entire code is below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct rec
{
int i;
float PI;
char A;
} Record;
typedef struct
{
char fname[20];
char lname[50];
char phone[15];
} Contact;
Record * arrayAlloc(int size);
char * stringAlloc(int size);
Contact * contactAlloc();
void structAlloc();
int main(void)
{
int *ptrInt;
Record * ptrRec;
int i = 0;
char * myName;
Contact * contacts;
ptrInt = (int *)malloc(sizeof(int));
int vIndex=0;
int displayMenu();
Contact * contactAlloc();
// void searchIndex();
void searchFirst();
void searchLast();
void searchPhone();
contacts = contactAlloc();
char choice;
choice = displayMenu();
while (choice !=5)\
{
if (choice == 1)
// searchIndex();
{
printf("Please enter the index of the contact you wish to view. \nThis should be a positive integer\n\n");
// fgets(vIndex, 700, stdin);
scanf("%d", &vIndex);
fgetc(stdin);
printf("The value of vIndex is %d", &vIndex);
printf("You have selected to view the %d contact.\nFirst name:\t%c. \nLast Name:\t%c. \nPhone Number:\t%c.\n\n ", &vIndex, contacts[vIndex].fname, contacts[vIndex].lname, contacts[vIndex].phone);
}
else if (choice == 2)
searchFirst();
else if (choice == 3)
searchLast();
else if (choice == 4)
searchPhone();
choice = displayMenu();
}
printf("Thank for you using this program.\n");
return 0;
}
int displayMenu()
{
int choice = 0;
while (choice!= 1 && choice != 2 && choice != 3 && choice != 4 && choice!=5)
{
printf("\nWelcome to the phone book application. Please choose from the following options:");
printf("\n\n\t 1) Search the phone book by index. \n\t 2) Search the phone book by first name. \n\t 3) Search the phone book by last name. \n\t 4) Search the phone book by phone number. \n\t 5) Quit.\n\n");
scanf("%d", &choice);
}
return choice;
}
Contact * contactAlloc()
{
FILE * fin;
int count = 0, i = 0;
char aLine[100];
Contact * ptrContact;
fin = fopen("entries.txt", "r");
if (fin != NULL)
{
while( fgets(aLine, sizeof(aLine), fin) != NULL )
{
count++;
}
fseek(fin, 0L, SEEK_SET);
count = count / 3;
ptrContact = (Contact *) calloc(count, sizeof(Contact));
count = 0;
while( fgets(aLine, sizeof(aLine), fin) != NULL )
{
if (aLine[strlen(aLine) - 1] == '\n')
{
aLine[strlen(aLine) - 1] = '\0';
}
if (i % 3 == 0)
{
strcpy(ptrContact[count].lname, aLine);
}
else if (i % 3 == 1)
{
strcpy(ptrContact[count].fname, aLine);
}
else if (i % 3 == 2)
{
strcpy(ptrContact[count].phone, aLine);
//printf("Line %d at count %d: %s\n", i, count, aLine);
count++;
}
i++;
}
//count=count*3;
printf("%d contacts loaded.\n\n", count);
fclose(fin);
}
return ptrContact;
}
/*
void searchIndex()
{
int vIndex=0;
printf("Please enter the index of the contact you wish to view. This should be a positive integer");
scanf("%d", &vIndex);
fgetc(stdin);
printf("You have selected to view the %d contact.\nFirst name:\t%c. \nLast Name:\t%c. Phone Number:\t%c.\n\n ", &vIndex, &Contact[vIndex].fname, &Contact[vIndex].lname, &Contact[vIndex].phone);
}
*/
void searchFirst()
{
}
void searchLast()
{
}
void searchPhone()
{
}
You are printing the address of vIndex instead of the value:
printf("The value of vIndex is %d", &vIndex);
Change this line to the following:
printf("The value of vIndex is %d", vIndex);