我試過你的代碼,但無法重現問題。以下代碼的工作方式正是您所期望的,它會提示您輸入名稱,等待您鍵入名稱,然后提示您輸入地址,等等。
我想知道你是否不需要在提示輸入更多信息之前閱讀stdin并清空它?
typedef struct {
char* name;
char* address;
}employeeRecord;
int readrecord(employeeRecord &record)
{
char name[50];
char address[100];
printf("\nenter the name:");
fgets(name, sizeof(name), stdin);
record.nameLength = strlen(name) + 1;
record.name = malloc(sizeof(char)*record.nameLength);
strcpy(record.name,name);
printf("\nenter the address:");
fgets(address, sizeof(address), stdin);
...
}
順便說一句,您想在strlen(name)中加1,而不是減去1。或者,如果希望名稱存儲在記錄中而不帶終止空值,則需要使用memcpy將字符串復制到記錄中,而不是strcpy。
編輯:
我從你的評論中看到
scanf
要讀取選擇值,這將在輸入緩沖區中留下一個,然后由第一個
fgets
打電話。相反,您應該使用fgets讀取選擇行,然后使用sscanf解析輸入中的值。這樣地
int choice;
char temp[50];
fgets(temp, sizeof(temp), stdin);
sscanf(temp, "%d", &choice);
這應該會使沖洗stdin的整個問題變得毫無意義。