从CString到char*/TCHAR*的转换
Conversion from CString to char*/TCHAR*
我很清楚将CString
转换为c风格字符的技术。其中一种是使用strcpy
/_tcscpy
,还有一种是使用CStrBuf
。
问题:
char Destination[100];
CStringA Source; // A is for simplicity and explicit ANSI specification.
Source = "This is source string."
现在我想要这个:
Destination = Source;
自动发生。嗯,这在逻辑上意味着在CString
类中编写转换操作符。但是,正如隐含的那样,我没有特权来更改CString
类。
我想写一个全局转换操作符和全局赋值操作符。但是它不起作用:
operator char* (const CStringA&); // Error - At least must be class-type
operator = ... // Won't work either - cannot be global.
是的,写函数是绝对可能的(最好是模板化的)。但是这涉及到调用函数,并且它不像赋值操作符那样流畅。
不能给数组赋值。这让你想要的变得不可能。而且,老实说,这是一件非常错误的事情——一个神奇数字大小的缓冲区?
好吧,我不想说这在任何方面都是值得推荐的,但是您可以劫持一些较少使用的操作符来快速破解:
void operator<<=(char * dst, const std::string & s)
{
std::strcpy(dst, s.c_str());
}
int main()
{
char buf[100];
std::string s = "Hello";
buf <<= s;
}
您甚至可以为静态大小的数组设置一个中等安全的模板版本:
template <typename TChar, unsigned int N>
inline void operator<<=(TChar (&dst)[N], const std::string & s)
{
std::strncpy(dst, s.c_str(), N);
}
CString
上的操作符不能解决这个问题,因为你需要复制到Destination
缓冲区,尽管这个赋值会改变Destination的值,这是不可能的。
无论如何,您需要一个操作符来实现这一行:
strcpy(Destination, LPCSTR(Source)); // + buffer overflow protection
如您所见,转换Source只是完成了一半。您仍然需要复制到目标缓冲区。
同样,我也不推荐这样做,因为Destination = Source
行完全误导了char[]
的语义。
唯一可能的赋值是初始化Destination:
char Destination[100] = Source;
相关文章:
- 如何在虚幻引擎4中将char*转换为TCHAR?
- 用于从 ANSI 字符串转换为 std::basic_string <TCHAR>的正确函数声明
- 删除unicode def后,无法将QString转换为TCHAR
- 如何将TCHAR转换为常量字符
- 将 std::string 转换为 const tchar*
- 将 std::string 转换为具有特殊字符的 FString (TCHAR / wstring)
- 正确的交叉平台从 std::string 转换为 'const TCHAR *'
- 从字符转换为 TCHAR 中获得奇怪的字符
- 使用 TCHAR 的错误,无法转换为wchar_t
- 无法将'TCHAR*'转换为'const char*'
- 将CHAR转换为TCHAR的最快捷、最优雅的方式
- 安全C++ std::字符串到 TCHAR * 转换
- TCHAR[]转换为字符串
- 如何在VC++中将TChar[]数组转换为std::string.语法帮助
- 如何将wchar_t*转换为TCHAR[](而不是TCHAR*)
- 如何将TCHAR转换为visualc++
- 从CString到char*/TCHAR*的转换
- visual c++中支持unicode char的从TCHAR到char*的转换
- 如何将TCHAR数组转换为std::string
- 在C/C++(ms)中,将char[]转换为tchar[]的最简单方法是什么