6

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

Eric Fortin
  • 7,533
  • 2
  • 25
  • 33
backspace
  • 299
  • 2
  • 3
  • 7
  • 2
    [`std::string` or `std::wstring`](http://en.cppreference.com/w/cpp/string/basic_string)? Or make your own `tstring` by using `std::basic_string`? – Some programmer dude Feb 05 '14 at 13:23

3 Answers3

5

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.

Eric Fortin
  • 7,533
  • 2
  • 25
  • 33
  • @JoachimPileborg You're right and probably better in this particular case. Thanks for the suggestion. Edited the answer to add it. – Eric Fortin Feb 05 '14 at 13:45
4

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.

Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
3
#include <tchar.h>

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

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

MSDN: _tcscat_s

Sebastian Ax
  • 1,240
  • 12
  • 11