0

这个问题我已经有一段时间了,我不确定如何解决它。

这是问题:

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 并更改文本,它会将向量的所有推送项更改为输入文本。任何人都可以帮忙吗?

4

1 回答 1

-1

您每次都将相同的指针推送到数组。按下按钮后,您必须为缓冲区的内容分配一个新字符串。

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::stringconst 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*数据指针。

于 2021-04-01T07:30:37.983 回答