比较组合框中的键入字符串及其项目

时间:2012-05-19 10:29:27

标签: c++ string combobox std

假设我有20个不同长度的字符串,每个字符串应该与以下内容类似:

TCHAR *itemText[...];
SendMessage(hwndCombobox, CB_GETLBTEXT, i, (LPARAM)itemText);

由于我有一个项目的索引,我想在for循环中使用上面的代码。 但由于每个项目的长度不同,我不能使用类似的东西:

int itemLength = SendMessage(hwndCombobox, CB_GETLBTEXTLEN, i, 0);
TCHAR *itemText[itemLength];

由于首先使用消息CB_GETLBTEXTLEN需要长度,因此需要获取长度。我知道我可以使用,例如TCHAR *itemText[1024];,但我个人不喜欢这种方式。

我还尝试使用newdelete,其他人建议我使用vectorstd::string,而不是delete pointers created by new in CallBack Function ,但这会导致另一个问题,即CB_GETLBTEXT所需的LPARAM参数需要A pointer to the buffer that receives the string.,因此以下代码不起作用,因为最后一个参数是std::string,而不是指针接收字符串:

int i;
Vec<std::string> itemText;
for (i = 0; i < itemCount; i++) {
    ......... // Don't know how to initialize a string with a specified length.
    SendMessage(win->hwndFindBox, CB_GETLBTEXT, i, (LPARAM)itemText.At(i));
}

我不知道如何初始化具有指定长度的std::string str

实际上,我想将组合框控件的编辑控件中的键入字符串与此组合框中的项目进行比较。您有什么建议可以解决这个问题或做我想做的事吗?

1 个答案:

答案 0 :(得分:1)

您可能误解了将std::vectorstd::string一起使用的建议。在读取ComboBox项目文本时,您应该使用std::vector<TCHAR>作为临时缓冲区(因为您无法直接写入std::basic_string使用的内部缓冲区),然后您可以将其复制到std::basic_string<TCHAR>之后如果需要:

std::basic_string<TCHAR> s;
int itemLength = SendMessage(hwndCombobox, CB_GETLBTEXTLEN, i, 0);
if (itemLength != CB_ERR)
{
    std::vector<TCHAR> buf(itemLength + 1 /* for NUL */);
    SendMessage(hwndCombobox, CB_GETLBTEXT, i, reinterpret_cast<LPARAM>(&buf[0]));

    s = &buf[0];
}

这可行,因为std::vector保证使用连续内存,因此&buf[0]应该等同于一个数组(假设buf不为空,但在这种情况下,我们保证它至少有1个元素。)

相关问题