我遇到这个问题已经有一段时间了,我不确定该如何解决它。
这是问题所在:
std::vector<const char*> arr = {};
static char input[48] = "";
ImGui::InputTextWithHint("##Input", "Put your input here", input, IM_ARRAYSIZE(input));
if (ImGui::Button("add to array")){
arr.pushback(input);
}当我按下add时,它会将输入添加到向量中,但如果我再次按下add并更改文本,它会将向量中所有推入的项都更改为输入文本。有人能帮上忙吗?
发布于 2021-04-01 15:30:38
您每次都会将相同的指针推送到数组。在按下按钮后,您必须使用缓冲区的内容分配一个新字符串。
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>来做同样的事情,这样当您将一个新元素推送到向量时,将调用接受const char*的std::string的构造函数(这有点类似于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。要在ImGUI中使用std::string,可以使用它的.data() (或.c_str())方法访问它的const char*数据指针。
https://stackoverflow.com/questions/66900088
复制相似问题