我正在尝试编写一个数据库来存储员工信息。这是我有问题的代码:
#include<stdio.h>
int main(){
char name[100], gender[100], email[100], id[10], phone[20];
FILE *fPtr;
fPtr=fopen("staffinfo.txt","w");
FILE *fPtr1;
fPtr1=fopen("staffinfo.txt","a+");
if (fPtr == NULL)
printf("Error in opening file\n");
if (fPtr1 == NULL)
printf("Error in opening file\n");
printf("\n===Add New Staff Profile===");
printf("\n\nPlease enter the following staff information.");
printf("\n\nStaff ID: ");
scanf("%s", &id);
fflush(stdin);
printf("Name\t: ");
fgets(name,100,stdin);
printf("Gender\t: ");
scanf("%s", &gender);
printf("Phone\t: ");
scanf("%s", &phone);
printf("Email\t: ");
scanf("%s", &email);
fprintf(fPtr, "Staff ID\t Name\t\t Gender\t\t Phone\t\t Email");
fprintf(fPtr1, "\n%s\t\t %s\t\t %s\t\t %s\t %s", id, name, gender, phone, email);
printf("\nSYSTEM: New Staff Profile is Added Successfully.");
fclose(fPtr);
fclose(fPtr1);
return 0;
}
输出给出:
===Add New Staff Profile===
Please enter the following staff information.
Staff ID: 1
Name : Carmen Gray
Gender : Female
Phone : 123-4567890
Email : carmen@live.com
SYSTEM: New Staff Profile is Added Successfully.
--------------------------------
Process exited with return value 0
Press any key to continue . . .
但是, text.file 中的输出与预期不符:
Staff ID Name Gender Phone Email
1 Carmen Gray
Female 123-4567890 carmen@live.com
问题在于这段代码:
fflush(stdin);
printf("Name\t: ");
fgets(name,100,stdin);
如果我使用 scanf 而不是 fgets,则无法存储带空格的字符串。谁能建议我如何使它工作?