c++ - 在 ImGui::InputText(...) 中使用 std::string
问题描述
调用ImGui::InputText()
需要一个char
数组,我需要从 a 初始化该数组,std::string
然后将内容传输回std::string
. 以最简单的形式:
char buf[255]{};
std::string s{"foo"};
void fn() {
strncpy( buf, s.c_str(), sizeof(buf)-1 );
ImGui::InputText( "Text", buf, sizeof(buf) );
s=buf;
}
buf
但是,让两个缓冲区(以及在其中分配的缓冲区std::string
)都做同样的事情似乎很浪费。我可以buf
通过仅使用std::string
和一个简单的包装器“X”来避免缓冲区和复制到缓冲区和从缓冲区复制。我不关心效率,我只想要调用站点上最简单的代码。这段代码确实有效,但它安全吗?有更好的方法吗?
class X {
public:
X(std::string& s) : s_{s} { s.resize(len_); }
~X() { s_.resize(strlen(s_.c_str())); }
operator char*(){ return s_.data(); }
static constexpr auto len() { return len_-1; }
private:
std::string& s_;
static constexpr auto len_=255;
};
std::string s{"foo"};
void fn() {
ImGui::InputText( "Text", X(s), X::len() );
}
解决方案
如果您想使用InputText()
withstd::string
或任何自定义动态字符串类型,请参阅 misc/cpp/imgui_stdlib.h 和 imgui_demo.cpp 中的注释。
杂项/cpp/imgui_stdlib.h
namespace ImGui
{
// ImGui::InputText() with std::string
// Because text input needs dynamic resizing, we need to setup a callback to grow the capacity
IMGUI_API bool InputText(const char* label, std::string* str, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool InputTextMultiline(const char* label, std::string* str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool InputTextWithHint(const char* label, const char* hint, std::string* str, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
}
你的第一个代码
std::string s{"foo"};
void fn() {
ImGui::InputText( "Text", &s );
}
阅读手册可以创造奇迹。
推荐阅读
- typescript - 如何在 Protractor-Jasmine-typescript html 报告日志中添加 Pass 语句
- mysql - 为什么使用 mysql 和 docker-compose 会发生访问被拒绝
- windows - 电子应用程序未显示 Windows 通知
- angular2-forms - Angular2如何处理.find方法中的空值
- java - 添加 Spring Security 会导致列和表丢失
- sql - Oracle SQL 比较聚合行
- git - 如何从本地和远程分支获取所有提交 SHA ID?
- c++ - 在主函数内启动数组(大小:20000001)抛出 SIGSEGV
- python - 在 cloudML 上使用 tf.hub 为诗人部署张量流
- twilio - Twilio,如何从父 Sid 获得 Child Sid?