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

StackOverflow https://stackoverflow.com/questions/944516

  •  09-09-2019
  •  | 
  •  

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

由于我习惯使用 VB6、C#、Ruby 进行字符串操作,因此我在 C++ 中编码很困难。但现在我花了 30 多分钟尝试将包含 2 个 guid 的字符串和一个字符串记录到调试窗口......而且它并没有变得容易,我已经遇到了 RPC_WSTR, std::wstringLPCWSTR

是否有简单(或任何)规则来了解它们之间的转换?还是只有在多年的折磨之后才会出现?

基本上,我正在寻找标准 API 和 MS 特定/Visual C++ 库中最常用的字符串类型;下次该做什么,我明白了

Error   8   error C2664: 'OutputDebugStringW' : cannot convert parameter 1 from 'std::wstring' to 'LPCWSTR'

更新: :我修复了^^^^编译错误。我正在寻找更全局的答案,而不是我作为示例列出的特定问题的解决方案。

有帮助吗?

解决方案

有两种内置字符串类型:

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

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

微软进一步将这些指针隐藏在许多宏后面。

LPCWSTR 是一个 指向常量宽字符串的长指针, ,或者换句话说,一个 const wchar_t*.

LPSTR 是一个 指向字符串的长指针, ,或者换句话说,一个 char* (不是常量)。

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

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

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

const char* cstr = "hello world";
std::string cppstr = cstr;

另一种方式则不太好:

std::string cppstr("hello world");
const char* cstr = cppstr.c_str();

那是, 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.

其他提示

OutputDebugStringW (myString.c_str ());

欢迎到C ++; - )

您可以只创建一个接受std::string的包装功能。然后,在功能提取c样式串,并传递给OutputDebugStringW

std::wstring std::string只是别名为std::basic_string<wchar_t>std::basic_string<char>

两者都有,需要一个C-串的.c_str()-方法,它返回一个传统的C形字符串指针(LPCWSTR等)和构造函数。

您可能想看看 CStdString 。这是一个跨平台的标准C ++ CString的实现,转换成其他大多数字符串类型很容易。使得几乎所有的字符串相关的头痛消失,它只是一个头文件。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top