的第一個問題是你的結構不正確。由於只有一個字節,因此您不能在名稱字段中存儲員工的姓名。你必須使它成爲一個數組(在這種情況下更簡單)或指向已分配內存的指針。
如果你想使它成爲一個數組,那麼你應該定義數組的最大尺寸。在我們的例子中,我們只是將它設爲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