我有以下结构和代码来填充它:
typedef struct {
char name[CONTACT_NAME_SIZE];
char surname[CONTACT_SURNAME_SIZE];
char address[CONTACT_ADDRESS_SIZE];
char phoneNumber[CONTACT_PHONENUMBER_SIZE];
} Contact;
...
char buffer[1024];
char phonebookItem[50];
printf("Name (max %d characters): ", CONTACT_NAME_SIZE);
fgets(buffer, sizeof(buffer), stdin);
memcpy(phonebookItem, buffer, sizeof(phonebookContacts[id].name));
strcpy(phonebookContacts[id].name, phonebookItem);
printf("Surname (max %d characters): ", CONTACT_SURNAME_SIZE);
fgets(buffer, sizeof(buffer), stdin);
memcpy(phonebookItem, buffer, sizeof(phonebookContacts[id].surname));
strcpy(phonebookContacts[id].surname, phonebookItem);
printf("Address (max %d characters): ", CONTACT_ADDRESS_SIZE);
fgets(buffer, sizeof(buffer), stdin);
memcpy(phonebookItem, buffer, sizeof(phonebookContacts[id].address));
strcpy(phonebookContacts[id].address, phonebookItem);
printf("Phone number (max %d characters): ", CONTACT_PHONENUMBER_SIZE);
fgets(buffer, sizeof(buffer), stdin);
memcpy(phonebookItem, buffer, sizeof(phonebookContacts[id].name));
strcpy(phonebookContacts[id].phoneNumber, phonebookItem);
问题是当我输入第一个字段的数据时,一切正常。但是当我输入下一个字段的数据时,我输入的所有内容(第一个和第二个输入)都写入第一个字段,依此类推......
示例:
Name (max 10 characters): 123456789*123456789
phonebookContacts[id].name = 123456789* -> OK
Surname (max 15 characters): 123456789*123456789*
phonebookContacts[id].name = 123456789*123456789*12345
phonebookContacts[id].surname = 123456789*12345
为什么会被覆盖?
答案 0 :(得分:-1)
而不是:
fgets(buffer, sizeof(buffer), stdin);
memcpy(phonebookItem, buffer, sizeof(phonebookContacts[id].name));
strcpy(phonebookContacts[id].name, phonebookItem);
试试这个:
memset(buffer, 0, sizeof(buffer)); // zero out all of buffer
fgets(buffer, sizeof(buffer), stdin); // accept up to n-1 input characters (last zero stays)
strncpy(phonebookContacts[id].name, buffer, CONTACT_NAME_SIZE-1); // copy data
或:
memset(buffer, 0, sizeof(buffer)); // zero out all of buffer
fgets(buffer, CONTACT_NAME_SIZE, stdin); // accept up to field-specific number of input characters
strcpy(phonebookContacts[id].name, buffer); // copy data
假设缓冲区的大小始终大于您可能提供的任何输入,并且其大小也大于您输入的字段中的任何或等于最大值。
编辑:为清晰起见添加了两个选项