Reputation: 127
I'm trying to code a function to retrieve the value between two tags or characters using CStrings, so far I haven't been able to do so.
CODE REMOVED
I'm pretty sure StartIndex and EndIndex have the right values, however I'm stuck at the last step, where I'm supposed to extract the substring from between the tags.
EDIT:// Got it working, thanks to Igor Tandetnik. If anyone knows why SubStr only prints correctly with wcout if I explicitly cast it with (LPCWSTR)
it would be greatly appreciated. I'm leaving the working code below in case someone else needs this or wants to improve it.
CString ExtractString(CString strSource, CString strStart, CString strEnd)
{
CString SubStr = L"";
int iEndIndex, iStartIndex = strSource.Find(strStart);
iStartIndex += strStart.GetLength();
iEndIndex = strSource.Find(strEnd, iStartIndex);
if (iStartIndex == -1 || iEndIndex == -1)
{
wcout << L"TAG not found!" << endl;
return SubStr;
}
SubStr = strSource.Mid(iStartIndex, (iEndIndex - iStartIndex));
SubStr.Trim();
return SubStr;
}
Upvotes: 1
Views: 1665
Reputation: 31629
If you pass std::wstring
to wcout
, it works fine because those guys know each other. wcout
will pick the right <<
operator for std::wstring
But C++ Standard Library and MFC are separate. wcout
doesn't know what to do with CString
, so it treats CString
object as const void*
, it uses operator<<(const void*)
to print an address.
Next step, CString
returns (const wchar_t*
) buffer. But wcout
had already decided on const void*
, so wcout
prints the address of that string buffer returned by CString
.
(const wchar_t*)
cast will instruct wcout
to use the right <<
operator. You can also use CString::GetString()
to let wcout
know that wide characters are being sent.
wcout << LPCWSTR(SubStr);
//or
wcout << SubStr.GetString();
Upvotes: 1