在 ImGui::InputText(...) 中使用 std::string

5 c++ imgui

对的调用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;
}
Run Code Online (Sandbox Code Playgroud)

然而,让两个缓冲区(buf以及其中分配的缓冲区std::string)都做同样的事情似乎很浪费。我可以通过仅使用一个简单的包装器“X”来避免buf缓冲区以及从缓冲区进行复制吗?std::string我不关心效率,我只想要调用站点最简单的代码。这段代码确实有效,但它安全吗?有更好的方法吗?

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() );
}
Run Code Online (Sandbox Code Playgroud)

S.M*_*.M. 11

如果您想使用InputText()任何std::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);
}
Run Code Online (Sandbox Code Playgroud)

你的第一个代码

std::string s{"foo"};
void fn() {    
    ImGui::InputText( "Text", &s );
}
Run Code Online (Sandbox Code Playgroud)

阅读手册会产生奇迹。

  • 您有这本精彩手册的链接吗?(不仅仅是示例代码) (11认同)
  • imgui_demo.cpp 多次有注释:“要将 InputText() 与 std::string 或任何其他自定义字符串类型连接,请参阅此演示的“文本输入 > 调整大小回调”部分,以及misc/cpp/imgui_stdlib.h文件”。再说一遍,阅读手册会产生奇迹。 (2认同)