C++ Combine 2 Tchar

社会主义新天地 提交于 2019-12-10 13:48:21

问题


I'm trying to combine 2 tchar.

char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);
TCHAR* appdatapath ="C:\\Users\\"+username+"\\AppData";

But I get error error at appdatapath line. How can I combine 2 tchar? Thanks


回答1:


Have a look at strcat and wcscat. You can't add char pointer with char array.

If you are on a windows machine, you can use _tcscat which will redirect to the right function to use depending on _UNICODE and _MBCS defines.

Might want to use the safe versions as well by appending _s to the function name.


As pointed in the comments, you can also use snprintf like so:

const size_t concatenated_size = 256;
char concatenated[concatenated_size];

snprintf(concatenated, concatenated_size, "C:\\Users\\%s\\AppData", username);

Since you have string literals before and after the runtime string, it is probably a better approach.




回答2:


To answer the question in the title: you concatenate two TCHAR strings using the _tcscat function.

However, there are other issues in your code related to this: GetUserName expects a LPTSTR, i.e. a pointer to a buffer TCHAR characters. Furthermore, there's another TCHAR usage in

TCHAR* appdatapath ="C:\\Users\\"+username+"\\AppData";

The issue with this is that the type to which TCHAR expands changes depending on whether _UNICODE is defined. In particular, if you set it, TCHAR (eventually) expands to wchar and hence GetUserName expects a wchar_t* but you pass a char*. Another issue is that you cannot concatenate C arrays using the + operator.

I suggest to stop worrying about TCHAR in the first place and always just compile with _UNICODE defined - and use wchar throughout your code. Also, since you're using C++, just use std::wstring:

wchar username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserNameW(username, &username_len);
std::wstring appdatapath = L"C:\\Users\\";
appdatapath += username;
appdatapath += L"\\AppData";

Last but not least: your entire code can probably be replaced with a call to the SHGetSpecialFolderPath function - pass CSIDL_APPDATA to it to get the "AppData" path.




回答3:


#include <tchar.h>

const size_t stringSize= 20;
TCHAR value[stringSize] = { 0 };

_tcscat_s(value, stringSize, TEXT("appendMe"));

MSDN: _tcscat_s



来源:https://stackoverflow.com/questions/21578455/c-combine-2-tchar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!