我有一個結構如何使用malloc和realloc在C中讀取和存儲任意長度的字符串?
typedef struct store
{
char name[11];
int age;
} store;
和主函數(下面是它的一部分):
int main()
{
int i=0;
int inputs;
char line[100];
char name[11];
char command[11];
store read[3000];
while(i < 3000 && gets(line) != NULL)
{
int tempage;
inputs = sscanf(line, "%10s %10s %d", command, name, &tempage);
if (inputs == 3)
{
if (strcmp(command, "register") == 0)
{
strncpy(read[i].name, name,10);
read[i].age = tempage;
i++;
....
我需要修改它,以便它可以讀取一行任意長度的,並存儲該行的名稱也是使用malloc和realloc的任意長度的字符串。
我該如何解決這個問題?
首先,**從不使用gets()**。決不。 – 2012-04-02 19:27:29
'寄存器讀取[3000]'嚇死我了! – 2012-04-02 19:29:20
@Greg好的,我會用fgets() – Draygon 2012-04-02 19:32:35