std::wstring: concatenation with + has no effect
Solution 1
As I found out the two NULL characters stored at the end of the string were the problem. Apparently std::wstring does not care about NULLs like good old C string does. If it thinks a string is 10 characters long, it does not care if some of those 10 characters are NULL characters. If you then append to that string, the additional characters get appended after the 10ths char. If the last characters of the string happen to be NULLs, you get:
C:\\SomePath\0\0\\*.*
Such a string cannot really be used anywhere.
How did I get the NULL characters at the end of the original string? I used wstring.resize() in some other function which pads the string with NULLs. I did this in order to pass &string[0] to a Windows API function expecting a LPWSTR.
Now that I know this does not work I use a true LPWSTR instead. That is a bit more clumsy, but it works. Coming from MFC, I thought I could use std::wstring like CString with its GetBuffer and Release methods.
Solution 2
This should work, and indeed works for me on VS2010, SP1:
#include <iostream>
#include <string>
int main()
{
const std::wstring sPath = L"C:\\SomePath";
const std::wstring sSearchPattern = sPath + L"\\*.*";
std::wcout << sSearchPattern << L'\n';
return 0;
}
This prints
C:\SomePath\*.*
for me.
Helge Klein
Author of uberAgent for Splunk (user experience and application performance monitoring), Delprof2 (user profile deletion), SetACL and SetACL Studio (permissions management).
Updated on June 24, 2022Comments
-
Helge Klein almost 2 years
The solution is probably obvious, but I do not see it. I have this simple C++ code:
// Build the search pattern // sPath is passed in as a parameter into this function trim_right_if(sPath, is_any_of(L"\\")); wstring sSearchPattern = sPath + L"\\*.*";
My problem is that the + operator has no effect (checked in debugger). The string
sSearchPattern
is initialized to the value ofsPath
only.Notes:
sPath
is awstring
.Example of what I want to achieve:
sSearchPattern -> C:\SomePath\*.*
More Info:
When I look at sPath in the debugger, I see two NULL characters after the last character. When I look at sSearchPattern, the "\*.*" is appended, but after the two NULL characters. Any explanation for that?