在c++中连接不同类型的字符串

Concatenating strings of different types in C++

本文关键字:同类型 字符串 连接 c++      更新时间:2023-10-16

如何在c++中连接以下charTCHAR变量?

TCHAR fileName[50];
TCHAR prefix[5] = "file_";
TCHAR ext[4] = ".csv";
char *id[10];
generateId(*id);

generateId(char *s)函数只是生成一个随机字符串。我需要让fileName变成类似file_randomIdGoesHere.csv的东西

我已经尝试过strncat(fileName, prefix, 5);,它适用于所有TCHAR变量,但不是char *,因为它需要const char *,所以也许有更好的方法,不知道如何将char *char **转换为const char *

任何想法?

我得到的错误与strncat(fileName, id, 10)error: cannot convert 'char**' to 'const char*'

您看到的错误是因为您的id数组声明错误。您声明了一个指针数组而不是字符数组。它应该更像这样:

char id[10];
generateId(id);

也就是说,您还将基于char的字符串文字分配给TCHAR数组,这意味着您没有为Unicode编译您的项目,否则此类分配将无法编译。因此,您不妨将TCHAR替换为char:

char fileName[50] = {0};
char prefix[] = "file_";
char ext[] = ".csv";
char id[10] = {0};
generateId(id);

然后将strncat()改为_snprintf():

_snprintf(filename, 49, "%s%s.cvs", prefix, id);

如果你真的想使用TCHAR,那么你需要将所有更改为TCHAR,并使用TEXT()宏:

TCHAR fileName[50] = {0};
TCHAR prefix[] = TEXT("file_");
TCHAR ext[] = TEXT(".csv");
TCHAR id[10] = {0};
generateId(id);
__sntprintf(filename, 49, TEXT("%s%s.cvs"), prefix, id);

如果不能将id更改为TCHAR,则必须执行运行时转换:

TCHAR fileName[50] = {0};
TCHAR prefix[] = TEXT("file_");
TCHAR ext[] = TEXT(".csv");
char id[10] = {0};
generateId(id);
#ifdef UNICODE
wchar_t id2[10] = {0};
MultiByteToWideChar(CP_ACP, 0, id, -1, id2, 10);
#else
char *id2 = id;
#endif
__sntprintf(filename, 49, TEXT("%s%s.cvs"), prefix, id2);

您应该做的第一件事是,由于您使用的是 c++ 而不是纯C,因此只需使用字符串类来表示您的字符串,并以比原始C风格字符数组更方便的方式管理它们。

在Windows c++编程环境中, CString 是一个非常方便的字符串类。您可以使用它的重载operator+(或+=)以一种方便、健壮和简单的方式连接字符串。

如果您的id存储在字符字符串中(作为ASCII字符串),如您在问题代码中所示:

char id[10];  
generateId(id);

你可以首先在它周围创建一个CString(这也将从char-string转换为TCHAR-string,特别是wchar_t-string,如果你正在使用Unicode构建,这是自VS2005以来的默认值):

const CString strId(id);

然后,您可以构建整个文件名字符串:

//
// Build file name using this format:
//
//    file_<generatedIdGoesHere>.csv
//
CString filename(_T("file_"));
filename += strId;
filename += _T(".csv");

作为替代,您也可以使用CString::Format方法,例如:

CString filename;
filename.Format(_T("file_%s.csv"), strId.GetString());

你可以简单地将CString的实例传递给Win32 api中的LPCTSTR参数,因为CString提供了到LPCTSTR的隐式转换(即const TCHAR*)。

要使用CString,您可以简单地使用#include <atlstr.h> .

首先,将char转换为TCHAR(参见如何将char*转换为TCHAR[]?)

然后,使用_tcscat()连接两个TCHAR字符串。

如果您不使用UNICODE字符表。那么你的TCHAR就相当于char.

TCHAR prefix[6] = "file_"; //don't forget to allocate space for null terminator ''
TCHAR ext[5] = ".csv"; // size is not 4, remember null terminator
char id[10] = "random"; // no need to use char* here
std::ostringstream oss;
oss << prefix << id << ext << std::endl;
std::cout << oss.str() << std::endl; // gives you file_random.csv as output