Hi,
I have an array of structures allowing user to enter info on 5 stocks. I have calculated initial cost, current cost, and profit. I have also bubble sorted the array of structures alphabetically by stock name and printed sorted array.
PROBLEM: I'm trying to save array of structures to a text file, retrieve it and then print the text file. I've successfully saved to the text file, but when I have the program retrieve the text file and print out the file, I get a problem. Why is the purchase date always being changed to "purchase" instead of staying as the date that is correctly listed in the text file?
Code:#include<stdio.h> #include<string.h> #define SIZE 5 struct Stock { char stock_name[9], purchase_date[9]; int num_shares; float buying_price, current_price, yearly_fees, initial_cost, current_cost, profit; }; void load(struct Stock s[], int n) { for(int i=0; i<n; i++) { printf("Enter stock name: "); gets(s[i].stock_name); printf("Enter purchase date: "); gets(s[i].purchase_date); printf("Enter number of shares: "); scanf("%d", &s[i].num_shares); printf("Enter buying price per share: "); scanf("%f", &s[i].buying_price); printf("Enter current price per share: "); scanf("%f", &s[i].current_price); printf("Enter yearly fees: "); scanf("%f", &s[i].yearly_fees); printf("\n"); s[i].initial_cost = s[i].num_shares * s[i].buying_price; s[i].current_cost = s[i].num_shares * s[i].current_price; s[i].profit = s[i].current_cost - s[i].initial_cost - s[i].yearly_fees; fflush(stdin); } } void sortStock(Stock s[], int n) { int i, j; char t[9]; for(i=0; i<n-1; i++) for(j=0; j<n-1; j++) if (strcmp(s[j].stock_name, s[j+1].stock_name)>0) { strcpy(t, s[j].stock_name); strcpy(s[j].stock_name, s[j+1].stock_name); strcpy(s[j+1].stock_name, t); } } void saveText(Stock s[], int n) { int j; FILE *f; f=fopen("c:\\stock_data.txt","w"); for(j=0; j<n; j++) { fprintf(f, "%s\n", s[j].stock_name); fprintf(f, "Purchase Date: %s\n", s[j].purchase_date); fprintf(f, "Intial Cost: $%0.2f\n", s[j].initial_cost); fprintf(f, "Current Cost: $%0.2f\n", s[j].current_cost); fprintf(f, "Profit: $%0.2f\n\n", s[j].profit); } fclose(f); } void retText(struct Stock s[], int n) { FILE *f; int j; f=fopen("c:\\stock_data.txt","r"); for(j=0; j<n; j++) { fgets(s[j].stock_name, sizeof(s[j].stock_name), f); fgets(s[j].purchase_date, sizeof(s[j].purchase_date),f); fscanf(f, "%f %f %f\n", s[j].initial_cost, s[j].current_cost, s[j].profit); } fclose(f); } void print(Stock s[], int n) { for(int j=0; j<n; j++) { printf("Stock Name: %s", s[j].stock_name); printf("\nPurchase Date: %s\n", s[j].purchase_date); printf("Initial Cost: $%0.2f\n", s[j].initial_cost); printf("Current Cost: $%0.2f\n", s[j].current_cost); printf("Profit: $%0.2f\n\n", s[j].profit); } } void main() { Stock s[SIZE]; load(s, SIZE); sortStock(s, SIZE); print(s, SIZE); saveText(s, SIZE); retText(s, SIZE); print(s, SIZE); }



LinkBack URL
About LinkBacks




I used to be an adventurer like you... then I took an arrow to the knee.