的第一个问题是你的结构不正确。由于只有一个字节,因此您不能在名称字段中存储员工的姓名。你必须使它成为一个数组(在这种情况下更简单)或指向已分配内存的指针。
如果你想使它成为一个数组,那么你应该定义数组的最大尺寸。在我们的例子中,我们只是将它设为100个字节,这将足以存储任何名称。
#define MAX_NAME 100
typedef struct employeeType
{
char name[MAX_NAME];
int employeeNumber;
float salary;
float taxPercentage;
}EMPLOYEE;
其次,你的功能命名很混乱。 enterDetails应该只填充你传递的结构。第三,你的输入细节应该接受一个指向EMPLOYEE结构的指针。如果你想将任何值传递给一个将会改变它的内容的函数,那么你只能使用指针(或者如果你使用C++,但基本上是一个指针)。所以enterDetails应该是,
void enterDetails(EMPLOYEE *details)
{
printf("\nEnter the employee's name ");
scanf("%s", details->name); // this isn't secure since it doesn't perform bound checking.
printf("\nEnter employee number ");
scanf("%d", &details->employeeNumber);
printf("\nEnter employee salary ");
scanf("%f", &details->salary);
printf("\nEnter tax percentage ");
scanf("%f", &details->taxPercentage);
}
最后,如果你想结构的内容存储到要给人阅读的,那么你应该格式化结构的内容和转储到一个文件的文件。
int writeToFile(EMPLOYEE *details) /* accepting the structure will work as well but it's faster and efficient to pass the structure's pointer */
{
FILE *file;
file = fopen("employees.txt","w");
if(file == NULL) {
printf("File error!!!");
return 0;
}
fprintf(file, "\nEmployee Name: %s", details->name);
fprintf(file, "\nEmployee Number: %d", details->employeeNumber);
fprintf(file, "\nSalary: %f", details->salary);
fprintf(file, "\nTax Percentage: %f", details->taxPercentage);
fclose(file)
return 1;
}
及主要
int main(void)
{
EMPLOYEE details;
enterDetails(&details); // passing the pointer here is a must
if (!writeToFile(&details)) { // passing the pointer since it's faster
printf("\nError writing to file");
return 1;
} else {
printf("\nSuccess!");
return 0;
}
}
而在你的情况,你不需要任何参数传递给主。但是如果你想知道如何传递参数,那么这里就是一个简单的例子。
int main(int argc, char **argv)
{
int i;
for (i = 0; i < argc; i++)
printf("\n%s", argv[i]);
return 0;
}
您可能是指'int main(){}'。 – 2011-04-28 09:20:32
@Cody:'int main(){}'不会做太多;-) – 2011-04-28 09:23:21
Hrm,至少它编译。我认为这显然不是重点。 – 2011-04-28 09:24:32