首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++ std::向量问题(imgui)

C++ std::向量问题(imgui)
EN

Stack Overflow用户
提问于 2021-04-01 15:24:14
回答 1查看 392关注 0票数 0

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

这是问题所在:

代码语言:javascript
复制
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并更改文本,它会将向量中所有推入的项都更改为输入文本。有人能帮上忙吗?

EN

回答 1

Stack Overflow用户

发布于 2021-04-01 15:30:38

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

代码语言:javascript
复制
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版本)。

所以只要

代码语言:javascript
复制
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*数据指针。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66900088

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档