在C中反序列化一个字符串
Deserializing a string in C
我发送的数据格式如下
1 2 5
1 3 6
1 4 9
我正在使用以下函数反序列化它们
void deserialize(RV** arr, char* msg){
int idx = 0;
char* line = strtok(msg, "\n");
RV rv;
rv.server1 = atoi(strtok(line, " "));
rv.server2 = atoi(strtok(NULL, " "));
rv.weight = atoi(strtok(NULL, " "));
memcpy(arr[idx], &rv, sizeof(rv));
idx++;
while (strtok(NULL, "\n") != NULL){
//printf("%s\n", line);
RV rv;
rv.server1 = atoi(strtok(NULL, " "));
rv.server2 = atoi(strtok(NULL, " "));
rv.weight = atoi(strtok(NULL, " "));
memcpy(arr[idx], &rv, sizeof(rv));
idx++;
}
}
这个returns第一行正确,但其余都是0
1 2 5
0 0 0
0 0 0
我做错了什么。任何帮助表示赞赏。
您遇到的一个问题是 strtok
function is not reentrant, which means you can't use it to tokenize two different strings. If you have strtok_s
you could use it, or you could use simple sscanf
每行的解析。
另一个问题是您没有在循环中获取新行。
您可以轻松地用类似这样的代码替换您的代码:
int deserialize(RV** arr, char* msg)
{
char *line = strtok(msg, "\n");
int idx = 0;
do
{
sscanf(line, "%d %d %d", &arr[idx]->server1, &arr[idx]->server2, &arr[idx]->weight);
++idx;
} while ((line = strtok(NULL, "\n")) != NULL);
return idx; // Return the number of lines we parsed
}
这假定消息中至少有一行(以换行符结尾)。另请注意,我写的是我头顶的代码,我没有测试过。
我发送的数据格式如下
1 2 5
1 3 6
1 4 9
我正在使用以下函数反序列化它们
void deserialize(RV** arr, char* msg){
int idx = 0;
char* line = strtok(msg, "\n");
RV rv;
rv.server1 = atoi(strtok(line, " "));
rv.server2 = atoi(strtok(NULL, " "));
rv.weight = atoi(strtok(NULL, " "));
memcpy(arr[idx], &rv, sizeof(rv));
idx++;
while (strtok(NULL, "\n") != NULL){
//printf("%s\n", line);
RV rv;
rv.server1 = atoi(strtok(NULL, " "));
rv.server2 = atoi(strtok(NULL, " "));
rv.weight = atoi(strtok(NULL, " "));
memcpy(arr[idx], &rv, sizeof(rv));
idx++;
}
}
这个returns第一行正确,但其余都是0
1 2 5
0 0 0
0 0 0
我做错了什么。任何帮助表示赞赏。
您遇到的一个问题是 strtok
function is not reentrant, which means you can't use it to tokenize two different strings. If you have strtok_s
you could use it, or you could use simple sscanf
每行的解析。
另一个问题是您没有在循环中获取新行。
您可以轻松地用类似这样的代码替换您的代码:
int deserialize(RV** arr, char* msg)
{
char *line = strtok(msg, "\n");
int idx = 0;
do
{
sscanf(line, "%d %d %d", &arr[idx]->server1, &arr[idx]->server2, &arr[idx]->weight);
++idx;
} while ((line = strtok(NULL, "\n")) != NULL);
return idx; // Return the number of lines we parsed
}
这假定消息中至少有一行(以换行符结尾)。另请注意,我写的是我头顶的代码,我没有测试过。