场景:socket 客户端将一个单向链表序列化后发送给服务端,服务端将之解析,重新构建单向链表。

Client.cpp

 1 //遍历链表,填充到缓冲区
 2 char* formatBuf(ListNode* p, char buf[100])
 3 {
 4     ListNode* tmp = p;
 5     //处理空链表
 6     if (tmp == NULL)
 7     {
 8         std::cout << "空链表!" << std::endl;
 9     }
10     memset(buf, 0, sizeof(buf));
11     while (tmp->next != NULL)
12     {
13         tmp = tmp->next;
14         //填充到缓冲区
20         char tmpStr[25];
21         sprintf(tmpStr, "%s/%s/%d ", tmp->Name, tmp->ID, tmp->Score); 
22         strcat(buf, tmpStr);
23     }
24     return buf;
25 }

Server.cpp

 1 //字符流解析
 2 void parseStr(char* buf, int len)
 3 {
 4     //新建链表
 5     ListNode *head, *node, *ptr;
 6     head = (ListNode*)malloc(sizeof(ListNode));
 7     int i =0, count = 0; 
 8     char* p = buf;//offset ptr
 9     ptr = head;
10     while(p < buf + len)
11     {
12         char name[5];
13         char id[10];
14         unsigned int s;
15         //字符串截取
16         sscanf(p, "%1s/%5s/%d", name, id, &s);
17         //printf("%s %s %d \n", name, id, s);
18         //申请空间
19         node = (ListNode*)malloc(sizeof(ListNode));
20         strcpy(node->Name, name);
21         strcpy(node->ID, id);
22         node->Score = s;
23         ptr->next = node;
24         node->next = NULL;
25         ptr = node;
26 
27         p += 11;//指针偏移
28     }
29     printList(head);
30 }

参考资料

【1】https://ask.csdn.net/questions/370828  (二楼回答,我根据回答修改的)