我正在尝试将从 strtok 返回的字符串添加到向量中,但由于某种原因,它只添加了文件中的最后一个字符串......
代码:
// read the remaining lines
// put address and ports into ipaddr and ports, respectively
for (unsigned i = 0; i < numStones; ++i) {
const char * item;
fgets(buffer, 255, fp);
//printf("%s", buffer);
item = strtok(buffer, " ");
printf("%s\n", item);
ipaddr.push_back(item);
item = strtok(NULL, "\n");
printf("%s\n", item);
ports.push_back(item);
}
#ifdef _DEBUG
for (unsigned i = 0; i < numStones; i++) {
printf("IP Address %d: %s\n", i, ipaddr.at(i));
printf("Port %d: %s\n", i, ports.at(i));
}
#endif
输出:
129.82.47.21
3360
129.82.47.22
5540
129.82.47.23
7732
129.82.47.24
8896
IP Address 0: 129.82.47.24
Port 0: 8896
IP Address 1: 129.82.47.24
Port 1: 8896
IP Address 2: 129.82.47.24
Port 2: 8896
IP Address 3: 129.82.47.24
Port 3: 8896
如您所见,代码从标记器获取正确的字符串,但没有将正确的字符串推送到向量。这让我发疯,帮助,谢谢!