天天看點

c語言讀取txt檔案 逗号,怎麼将txt中帶逗号的資料導入定義好的資料結構中

該樓層疑似違規已被系統折疊 隐藏此樓檢視此樓

#include

#include

struct student

{

int phone[12];

int grade[4];

int sno[11];

char sname[8];

char sex[5];

};

int main()

{

struct student *v = NULL;

FILE *fp=fopen("G://new.txt","r");

if(fp==NULL)

{

printf("文本打開錯誤/n");

return -1;

}

int i=0;

char c[9999];

v = (struct student*)malloc(sizeof(struct student));

while(!feof(fp))//檔案指針還未到達檔案末尾時,輸出檔案中資料//原理說明:feof(fp)有兩個傳回值:如果遇到檔案結束,函數feof(fp)的值為非零值,否則為0

{

fscanf(fp,"%[^,]%",&c);

//printf("%d/n",c);

}

char * split = ",";

char * p;

char *a[9999];

int j=0,k;

p = strtok (c,split);

while(p!=NULL)

{

//printf ("%s\n",p);

a[j]=p;j++;

p = strtok(NULL,split); //用逗号分割資料,并把資料存入指針數組a中

}

//for(j=0;j<10;j++)

//printf("%s\n",a[j]);

for(i=0;i<4;i++)

{

strcpy(v[i].sno,a[i*5]);

strcpy(v[i].sname,a[5*i+1]);

strcpy(v[i].sex,a[5*i+2]);

strcpy(v[i].phone,a[5*i+3]);

strcpy(v[i].grade,a[5*i+4]);

printf("學号:%s,姓名:%s,性别:%s,聯系方式:%s,成績:%s\n",v[i].sno,v[i].sname,v[i].sex,v[i].phone,v[i].grade);

// printf("%s",v[i].sno);

}

fclose(fp);

system("pause");

return 0;

}