[英]How can I get a const value for the size of a string in C++?
我需要能夠使用ImGui
文本框,但是它們不使用const char*
或std::string
所以我需要將字符串轉換為char
數組。 但是,問題在於我需要我的char
數組與字符串 (+1) 的大小相同。 我收到一個錯誤,說它在聲明中需要是常量值,但我需要能夠訪問字符串的大小並創建一個將該值保持為常量的變量。 這可能嗎? 這是代碼:
static std::string text = "";
static bool read_only = false;
char txt[text.size() + 1] = text;
ImGui::Begin("Window");
ImGui::InputTextMultiline("Textbox", txt, IM_ARRAYSIZE(txt), ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16), ImGuiInputTextFlags_AllowTabInput | (read_only ? ImGuiInputTextFlags_ReadOnly : 0));
ImGui::End();
ImGui::InputTextMultiline 的格式是這樣的:
bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0,0), ImGuiInputTextFlags flags = 0, ImGuiTextEditCallback callback = NULL, void* user_data = NULL)
編輯:文本框需要是任意大小,並且在編譯時不受 static 常量值的限制,而是動態大小,以便字符串也是如此。
使用本地char
緩沖區來完成您想要的。 沒有操作系統調用來分配 memory,您應該知道您希望最大允許輸入是什么。
這個 function 並沒有真正做任何事情。 獲得輸入后,您需要將數據復制到std::string
或其他東西來處理它。
std::string get_text_input(std::size_t arbitrary_size) {
char* buf = new char[arbitrary_size];
ImGui::Begin("Window");
ImGui::InputTextMultiline("Textbox", buf, arbitrary_size, ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16), ImGuiInputTextFlags_AllowTabInput | (read_only ? ImGuiInputTextFlags_ReadOnly : 0));
ImGui::End();
std::string ret(buf);
delete[] buf;
return ret;
}
以上無視。 您應該使用這個 function 簽名: https://github.com/ocornut/imgui/blob/01cc6660395032714e7a991eba679a9c69b00stdlib/cpp#L54b0_c5b.m
bool ImGui::InputTextMultiline(const char* label, std::string* str, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.