C++中最常用的字符串类型是什么以及如何在它们之间进行转换?

Gis*_*shu 4 string types visual-c++

或者下次C++编译器扭曲你的手臂以转换为2个任意字符串类型只是为了弄乱你时,如何不杀死自己或某人?

我很难用C++编写代码,因为我习惯使用VB6,C#,Ruby来进行字符串操作.但是现在我花了超过30分钟试图将包含2个guid和一个字符串的字符串记录到调试窗口......并且它没有变得更容易而且我已经遇到了RPC_WSTR,std::wstring并且LPCWSTR

是否有简单(或任何)规则来了解它们之间的转换?或者只是经过多年的折磨才能实现?

基本上我正在寻找标准API和MS特定/ Visual C++库中最常用的字符串类型; 我知道下次该怎么办

Error   8   error C2664: 'OutputDebugStringW' : cannot convert parameter 1 from 'std::wstring' to 'LPCWSTR'
Run Code Online (Sandbox Code Playgroud)

更新:我修复了^^^^编译错误.我正在寻找一个更全面的答案,而不是我列举的具体问题的解决方案.

jal*_*alf 9

有两种内置字符串类型:

  • C++字符串使用std :: string类(宽字符为std :: wstring)
  • C风格的字符串是const char指针const char*)(或const wchar_t*)

两者都可以在C++代码中使用.大多数API(包括Windows)都是用C语言编写的,因此它们使用char指针而不是std :: string类.

微软进一步隐藏了许多宏背后的这些指针.

LPCWSTR是Const宽字符串长指针,换句话说,是const wchar_t*.

LPSTR是String长指针,换句话说,是一个char*(不是const).

他们还有一些,但是一旦你知道了前几个,它们应该很容易猜到.它们还具有*TSTR变体,其中T用于指示这可能是常规字符还是宽字符,具体取决于是否在项目中启用了UNICODE.如果定义了UNICODE,则LPCTSTR解析为LPCWSTR,否则解析为LPCSTR.

所以,在使用字符串时,您只需要知道我在顶部列出的两种类型.其余的只是char指针版本的各种变体的宏.

从char指针转换为字符串很简单:

const char* cstr = "hello world";
std::string cppstr = cstr;
Run Code Online (Sandbox Code Playgroud)

而另一种方式并不多:

std::string cppstr("hello world");
const char* cstr = cppstr.c_str();
Run Code Online (Sandbox Code Playgroud)

也就是说,std::string在构造函数中将C样式的字符串作为参数.它有一个c_str()返回C风格字符串的成员函数.

一些常用的库定义了自己的字符串类型,在这些情况下,您必须检查文档中它们如何与"正确的"字符串类进行互操作.

您通常应该更喜欢C++ std::string类,因为与char指针不同,它们表现为字符串.例如:

std:string a = "hello ";
std:string b = "world";
std:string c = a + b; // c now contains "hello world"

const char* a = "hello ";
const char* b = "world";
const char* c = a + b; // error, you can't add two pointers

std:string a = "hello worl";
char b = 'd';
std:string c = a + b; // c now contains "hello world"

const char* a = "hello worl";
char b = 'd';
const char* c = a + b; // Doesn't cause an error, but won't do what you expect either. the char 'd' is converted to an int, and added to the pointer `a`. You're doing pointer arithmetic rather than string manipulation.
Run Code Online (Sandbox Code Playgroud)