gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:52:53 24 4
gpt4 key购买 nike

ImGui::InputText() 的调用需要一个 char 数组,我需要从 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 中分配的缓冲区)都做同样的事情似乎很浪费。我可以通过仅使用 std::string 和一个简单的包装器“X”来避免 buf 缓冲区以及与它之间的复制吗?我不关心效率,我只想要调用站点上最简单的代码。这段代码确实有效,但它安全吗?有更好的方法吗?

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()std::string 或任何自定义动态字符串类型一起使用,请参阅 misc/cpp/imgui_stdlib.h 和 imgui_demo 中的注释。 cpp.

misc/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 );
}

阅读手册可以创造奇迹。

关于c++ - 在 ImGui::InputText(...) 中使用 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69046648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com