首页 > 解决方案 > 在 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() );
}

标签: c++imgui

解决方案


如果您想使用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 );
}

阅读手册可以创造奇迹。


推荐阅读