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

标签 string visual-c++ types

或者下一次 C++ 编译器扭动你的 ARM 以在 2 种任意字符串类型之间进行转换只是为了惹你生气时,如何不杀死自己或某人?

由于我习惯于 VB6、C#、Ruby 进行字符串操作,因此我很难用 C++ 进行编码。但是现在我已经花了 30 多分钟试图将包含 2 个 guids 和一个字符串的字符串记录到调试窗口......而且它并没有变得更容易
我已经见过 RPC_WSTRstd::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 类。

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

    LPCWSTR 是一个指向 Const Wide String 的长指针,或者换句话说,一个 const wchar_t*

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

    他们还有一些,但一旦你知道前几个,他们应该很容易猜到。它们还有 *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.
    

    关于string - C++ 中最常用的字符串类型是什么以及如何在它们之间进行转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/944516/

    相关文章:

    sql - 来自反斜杠的 PostgreSQL 语法错误?

    c - 如何将字符串分配给 C 中的字符指针?

    c++ - std::string header 仅在 Visual Studio 中吗?

    c++ - vector 之间的转换是否定义了行为?

    c++ - 可能具有长度为零的数组的模板化数据类型

    c - C 中的动态 3D 可变列字符数组操作

    javascript - 标记特定字符串替换

    c++ - 将 _beginthread 返回的 uintptr_t 转换为 HANDLE 是否安全?

    java - 关于java中泛型转换的一些知识

    sql-server-2005 - Sql Server 2005 中的时间数据类型