Re: VC++ 2005 replace _bstr_t
Dave King <noobprog@gmail.com> wrote:
I've got a C++ app BHO i'm working on. I'm having trouble escaping
values in a _bstr_t for xml. Here's my code.
void Replace(_bstr_t& strSource, _bstr_t& strFind, _bstr_t& strRep)
{
wstring tmp((wchar_t*)strSource);
wstring::size_type begidx = tmp.find((wchar_t*)strFind);
while(begidx != wstring::npos) {
tmp.replace(begidx, strFind.length(), (wchar_t*)strRep);
begidx = tmp.find_first_of((wchar_t*)strFind, begidx +
strFind.length(), begidx);
The last parameter of three-parameter overload of find_first_of is the
length of the string pointed to by the first parameter. Clearly begidx
has nothing to do with the length of strFind. Anyway, why do you use
find_first_of() and not plain old find(), as you do at the beginning?
Make it
begidx = tmp.find(strFind, begidx + strRep.length());
void escapeXML(_bstr_t& strSource)
{
_bstr_t strFind("<");
_bstr_t strRep("<");
Replace(strSource, strFind, strRep);
_bstr_t strFind2(">");
_bstr_t strRep2(">");
Replace(strSource, strFind2, strRep2);
_bstr_t strFind3("&");
_bstr_t strRep3("&");
Suppose escapeXML is called with "<>". After the first Replace call it
becomes "<>". After the second, "<>". After the third,
"&lt;&gt;" . Do you see a problem here?
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925