C++ Combine 2 Tchar
Asked Answered
P

3

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

Parapodium answered 5/2, 2014 at 13:18 Comment(1)
std::string or std::wstring? Or make your own tstring by using std::basic_string<TCHAR>?Servitor
K
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.

Kingbolt answered 5/2, 2014 at 13:20 Comment(1)
@JoachimPileborg You're right and probably better in this particular case. Thanks for the suggestion. Edited the answer to add it.Kingbolt
M
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.

Mulvaney answered 5/2, 2014 at 13:46 Comment(0)
A
3
#include <tchar.h>

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

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

MSDN: _tcscat_s

Automata answered 2/11, 2018 at 15:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.