strings corrupting?

Hey its been a while since i'v done anything with c++ but i'v just started to get back into it, just making little apps n stuff, i'v never had this kind of problem before, using Microsoft visual c++ 8, szAppPath comes out fine, but once i try adding "\\settings.ini" it turns szAppSettingsPath into Chinese symbols, just wondering if anyone would know why?

1
2
3
4
5
6
char szAppPath[800];
char szAppSettingsPath[800];

GetCurrentDirectory(800,(LPWSTR)szAppPath);
sprintf( szAppSettingsPath, "%s\\Settings.ini", szAppPath );
MessageBox(0,(LPCWSTR)szAppSettingsPath,0,0);
You're cast is the problem.

You're using the wide string versions of the API. You should either use wide strings, use the narrow API or write your code in an agnostic way.

To use wide strings, you code will look like:
1
2
3
4
5
6
wchar_t szAppPath[800];
wchar_t szAppSettingsPath[800];

GetCurrentDirectory(800, szAppPath);
swprintf(szAppSettingsPath, L"%s\\Settings.ini", szAppPath);
MessageBox(0, szAppSettingsPath, 0, MB_OK);


You can force the narrow API by changing your project settings, and that undefines _UNICODE. Then you remove the casts from your code and it will work.

See:
http://msdn.microsoft.com/en-us/library/ybk95axf%28v=VS.71%29.aspx
Actually, to use wide strings the code must explicitly call the Wide versions of the functions. You only use the agnostic names if your entire code is written in an agnostic way:

1
2
3
4
5
6
wchar_t szAppPath[800];
wchar_t szAppSettingsPath[800];

GetCurrentDirectoryW(800, szAppPath);
swprintf(szAppSettingsPath, L"%s\\Settings.ini", szAppPath);
MessageBoxW(0, szAppSettingsPath, 0, MB_OK);


Note the addition of the W to the function names. If you use char and char-related data types, then you must change the W for an A.
Topic archived. No new replies allowed.