我正在尝试将从 strtok 返回的字符串添加到 vector 中,但由于某种原因它只添加了文件中的最后一个字符串...
代码:
// 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
如您所见,代码从分词器获取正确的字符串,但没有将正确的字符串推送到 vector 。这让我抓狂,求助,谢谢!
最佳答案
因为您在不分配新内存的情况下推送指针。您总是提供指向缓冲区内某个位置的指针。
在 C 中你会使用 strdup
复制字符串。
在 C++ 中,您通常会构造一个 std::string
并将它们存储在您的 vector 中而不是 char *
.但是,您可能有自己的内存管理方案,其中包含存储在某处的字符串缓冲区。或者你可以使用 strdup
如果你愿意的话。
我基本同意 Jonathan Potter 对另一个答案的评论:
Storing pointers in vectors should be discouraged
如果您是编程新手,您应该 100% 采纳该建议。当您更高级时,有时将指针放入 vector 中是完全合法的。
[编辑] 澄清。
快速修复是这样的(是的,我们通常应该检查 strdup
没有返回 NULL
):
ports.push_back(strdup(item));
但这会产生清理工作,因为当您完成 vector 时,您拥有所有这些需要释放的指针:
for( int i = 0; i < ports.size(); i++ ) free(ports[i]);
更好的解决方法是使用 std::vector<std::string>
作为您的数据类型,它将为您处理内存。
关于c++ - 将字符串添加到 vector<const char *> 会导致 strtok() 出现奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19085528/