-1

我正在使用 ImGui 并尝试向我的 const char * 添加一个数组项,以便我可以显示所选的项。我该怎么做?它显示随机字母,而不是我想要的。

static const char* FruitsList[] = { "Mango", "Apple", "Pear", "Bannana"};
indexFruit = 2;
const char * chosenFruitText = "Chosen Fruit"  + char(FruitsList[indexFruit]);
ImGui::ListBox(chosenFruitText , &indexFruit , FruitsList, IM_ARRAYSIZE(FruitsList));
4

2 回答 2

1

您不能将char/附加const char*const char[](您的字符串文字)。但是您可以连接 astd::string和字符串文字,例如:

static const std::string FruitsList[] = { "Mango", "Apple", "Pear", "Bannana"};
indexFruit = 2;
std::string chosenFruitText = "Chosen Fruit" + FruitsList[indexFruit];
ImGui::ListBox(chosenFruitText.c_str(), &indexFruit, FruitsList, IM_ARRAYSIZE(FruitsList));

否则,您将不得不做更多类似的事情:

static const char* FruitsList[] = { "Mango", "Apple", "Pear", "Bannana"};
indexFruit = 2;
char chosenFruitText[22] = "Chosen Fruit: ";
strcpy(chosenFruitText+14, FruitsList[indexFruit]);
ImGui::ListBox(chosenFruitText, &indexFruit, FruitsList, IM_ARRAYSIZE(FruitsList));
于 2021-08-13T00:35:09.790 回答
0

C 编程语言中没有字符串操作,不像您的代码所暗示的那样。在表达式“const char* ChosenFruit = ...”中,您告诉编译器您想要将包含“Chosen Fruit”的数组的地址与 FruitsList 中第三个字符串的地址(您将其截断为'char' 因为类型转换),并将结果分配给 ChosenFruit。ChosenFruit 只是指向内存中很可能不包含可打印字符的某个遥远位置。

要在 C 中连接两个字符串,您必须分配一个足够大的新数组来保存结果,并显式复制两个字符串的字符。您可以使用“strcpy()”和“strcat()”函数进行复制:

const char* s1 = "Hello ";
const char* s2 = "world!";
char s3[32]; /* big enough to hold s1 and s2 */
strcpy( s3, s1 ); /* copy s1 to s3 */
strcat( s3, s2 ); /* copy s1 to end of s3 */

你可以在 C++ 中做同样的事情,但是使用 C++ 标准库中的“std::string”对象可以说是更安全和更好的做法。'std::string' 对象自动分配从堆中保存字符串所需的内存量,在不再需要时自动释放此内存,并实现一个版本的 '+' 运算符来满足您的需求(级联):

#include <string>

static const std::string Fruits[] = { "Mango", "Apple", "Pear", "Banana" };
static const std::string Prefix = "Chosen Fruit ";
std::string ChosenFruit = Prefix + Fruits[index];

表达式“ChosenFruit = Prefix + ...”的意思是“调用以两个 'std::string' 对象作为参数的 '+' 运算符的版本”。此“+”运算符连接两个字符串并返回包含结果的新“std::string”对象。

于 2021-08-13T00:50:45.453 回答