简体   繁体   English

如何将char与TCHAR数组连接?

[英]How concatenate a char with TCHAR array?

I want concatenate a random string with a directory name and the final result must be something like this: 我想用目录名称连接一个随机字符串,最终结果必须是这样的:

C:\\Program Files (x86)\\AAAFFF1334 C:\\ Program档案(x86)\\ AAAFFF1334

On following code this part: " AAAFFF1334 " comes strange characters see: 在以下代码的这一部分:“ AAAFFF1334 ”出现奇怪的字符,请参见:

在此处输入图片说明

What must be made to fix this? 必须采取什么措施来解决此问题?

TCHAR mydir[MAX_PATH];

void gen_random(char *s, const int len) {
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";

    for (int i = 0; i < len; ++i) {
        s[i] = alphanum[rand() % (sizeof(alphanum)-1)];
    }

    s[len] = 0;
}

// main

TCHAR szProgramFiles[MAX_PATH];
HRESULT hProgramFiles = SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, SHGFP_TYPE_CURRENT, szProgramFiles);

char str;

gen_random(&str, 10);

wsprintf(mydir, TEXT("%s\\%s"), szProgramFiles, str);

gen_random should get char array with at least 11 characters (10 for size + 1 for terminating null). gen_random应该获得至少11个字符的char数组(大小为10个字符,终止为null的则为1个字符)。

So it should be: 因此应该是:

char str[10+1]; //or char str[11];
gen_random(str, 10);

in addition, the format string should be: "%s\\\\%hs" , the first is TCHAR* type (if UNICODE defined wchar_t* if not char* ) the second is always char* type. 此外,格式字符串应为: "%s\\\\%hs" ,第一个为TCHAR*类型(如果UNICODE定义了wchar_t*如果不是char* ),第二个始终为char*类型。

hs, hS hs,hS

String. 串。 This value is always interpreted as type LPSTR, even when the calling application defines Unicode. 即使调用应用程序定义了Unicode,该值也始终被解释为LPSTR类型。

look here 看这里

Note: in Microsoft documentation: 注意:在Microsoft文档中:

  • LPSTR = always char* LPSTR =始终为char*
  • LPWSTR = always wchar_t* LPWSTR =总是wchar_t*
  • LPTSTR = TCHAR* (if UNICODE defined: wchar_t* , else: char* ) LPTSTR = TCHAR* (如果定义了UNICODE: wchar_t* ,否则: char*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM