Reputation: 1332
Suppose I have 20 string of different length, each of them is supposed to obtained similar to the following:
TCHAR *itemText[...];
SendMessage(hwndCombobox, CB_GETLBTEXT, i, (LPARAM)itemText);
Since I have an index for the items, I would like to use the above code in a for loop. But because each item has different length, I can't use something like:
int itemLength = SendMessage(hwndCombobox, CB_GETLBTEXTLEN, i, 0);
TCHAR *itemText[itemLength];
Since using the message CB_GETLBTEXTLEN
require the length at first, it is necessary to get the length. I know I can just use, for example, TCHAR *itemText[1024];
, but I don't like this way personally.
I also tried to use new
and delete
, and other people suggest me to use vector
along with std::string
instead, as in this post delete pointers created by new in CallBack Function, but that leads to another problem in that the LPARAM parameter needed for CB_GETLBTEXT
requires A pointer to the buffer that receives the string.
, so the following code doesn't work, since the last parameter is std::string
, rather than a pointer which receives strings:
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));
}
I don't neither know how to initialize a std::string str
with a specified length.
In fact, I would like to compare the typed string in the edit control of a combobox control with the items on this combobox. Do you have any suggestion to solve this problem or to do what I want to do?
Upvotes: 0
Views: 555
Reputation: 90175
You might have misunderstood suggestions to use std::vector
with std::string
. You should use std::vector<TCHAR>
as a temporary buffer when reading the ComboBox item text (because you cannot write directly to the internal buffer used by std::basic_string
), and then you can copy that into a std::basic_string<TCHAR>
afterward if desired:
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];
}
This works because std::vector
is guaranteed to use contiguous memory, so &buf[0]
should be equivalent to an array (assuming that buf
is not empty, but in this case, we guarantee that it has at least 1 element).
Upvotes: 1