#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// number of salesman
#define SIZE 100
// salesman_type structure definition
typedef struct{
int ID; // salesman id
char id_txt[6]; // salesman id for txt file
char name[50]; // salesman name
double hor_total; // total sales amount of a salesman
}salesman_type; // end structure salesman_type
salesman_type salesman[SIZE];// synonym for salesman_type
// function prototype
int sale_menu();
void modifySales();
// sales processing system menu function
int sale_menu()
{
int menu;
system("cls");
printf("Sales Processing System\n");
printf("-----------------------\n\n");
printf("1. Add Salesman Records\n");
printf("2. Reports Generation\n");
printf("3. Modify Salesman Records\n");
printf("4. Delete Salesman Records\n\n");
printf("0. Exit\n");
printf("Your choice: ");
scanf("%d", &menu);
return menu;
printf("\n");
}// end function sale_menu
// modify salesman records function
void modifySales()
{
FILE *salesPtr; // sales.txt file pointer
FILE *salesmanPtr; // salesman.txt file pointer
int a = 1, b, modify; // counter
double sale[SIZE][4]; // quartely sales amount
// fopen opens the file; exits program if file cannot be opened
if ( (salesPtr = fopen("sales.txt","r+")) == NULL )
{
printf("Cannot open sales.txt\n"); // display error message
system("pause"); // pause program before it exits
exit(-1); // end program
} // end if
else
{
// prompt and read salesman id
printf("\nSalesman ID (NO.): ");
scanf("%d",&modify);
// if it is not required salesman id
while (a != modify)
{
fscanf(salesPtr,"%*[^\n]\n");
a++;
}
fscanf(salesPtr,"%*[^|]|", salesman[0].id_txt);
// read quarterly sales amount
for (b=0; b<4; b++)
{
// prompt and read quarterly sales amount
printf("Quarter %d: ", b+1);
scanf("%lf",&sale[0][b]);
// end with "|" symbol if b is less than 3
if(b<3)
{
fprintf(salesPtr,"%.2f|",sale[0][b]);
}
else
{
fprintf(salesPtr,"%.2f\n",sale[0][b]);
}
} // end for
} // end else
fclose(salesPtr); // fclose close the file
} // end function modifySales
// function main begins program execution
int main()
{
// variable declaration
int a, b, c = 0, last; // counter
int getMenu = 10, getReport = 10; // menu selector
while (getMenu != 0)
{
// call and assign sale_menu function to getMenu
// Execute command based on user input
switch(getMenu = sale_menu())
{
case 1:
break;
case 2:
break;
case 3:
modifySales();
break;
} // end switch
}// end while
return 0;
} // end main
重现问题的步骤 1)选择3.修改销售员记录 2)为销售员ID输入1 3)季度销售额的所有输入1
我预计季度销售额的第一个销售人员全部变为1,但事实并非如此。我的代码出了什么问题?
答案 0 :(得分:0)
你的做法是错误的。您试图混合读取和写入相同的文件,而不关注您正在编写的文件中的确切位置。最好从旧文件中读取并写入新文件。