您每次都将相同的指针推送到数组。按下按钮后,您必须为缓冲区的内容分配一个新字符串。
if (ImGui::Button("add to array")){
char* inputS = (char*)malloc((strlen(input) + 1) * sizeof(*input)); // allocate a separate string
strcpy(inputS, input); // copy until the first \0 byte is reached
arr.pushback(inputS);
}
这是 C 风格,有些人可能不想在现代 C++ 中看到。您可以通过将数组声明为 来做同样的事情,std::vector<std::string>
这样当您将新元素推送到向量时,将调用该构造函数std::string
(const char*
这有点类似于 C 版本)。
所以就
std::vector<std::string> arr;
if (ImGui::Button("add to array")){
arr.pushback(input); // const char* input will be copied to the new std::string element of the array
}
ImGUI 是一个 C-API,这意味着它不理解std::string
. 要std::string
与 ImGUI 一起使用,您可以使用它的.data()
(或.c_str()
)方法来访问它的const char*
数据指针。