简体   繁体   中英

How can I get a const value for the size of a string in C++?

I need to be able to use ImGui textboxes, however they don't take const char* or std::string so I need to convert a string to a char array. The problem with this is, however, that I need my char array to be the same size as the string (+1). I get an error saying it needs to be constant value in declaration but I need to be able to access the string's size and make a variable that holds that value as constant. Is this possible? Here is the code:

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();
         

The format for the ImGui::InputTextMultiline is this:

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)

Edit: The textbox needs to be arbitrary size and not limited by a static const value at compile time, rather a dynamic size such that strings are aswell.

Use a local char buffer to accomplish what you want. There's no OS call to allocate memory, and you should have an idea of what you want your maximum allowable input to be.

This function doesn't really do anything. After you get the input, you'll need to copy the data into a std::string or something else to do stuff with it.

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;
}

Disregard the above. You should use this function signature: https://github.com/ocornut/imgui/blob/01cc6660395032714e7a991eba679a9c69b00c5b/misc/cpp/imgui_stdlib.cpp#L54

bool ImGui::InputTextMultiline(const char* label, std::string* str, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM