代码之家  ›  专栏  ›  技术社区  ›  Gishu

C++中使用最多的字符串类型以及如何在它们之间转换?

  •  4
  • Gishu  · 技术社区  · 15 年前

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

    我有一个艰难的时间编码在C++中,因为我习惯于VB6,C,露比,字符串操作。但现在我花了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'
    

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

    6 回复  |  直到 8 年前
        1
  •  9
  •   Banderi jalf    8 年前

    有两种内置字符串类型:

    • C++字符串使用STD::String类(STD::WString用于宽字符)
    • C样式字符串是const char指针const char*)(或 const wchar_t* )

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

    微软还隐藏了一些宏背后的这些指针。

    LPCWSTR是一个 指向常量范围字符串的长指针 或者换句话说,a 康斯特瓦查特 .

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

    他们还有一把,但一旦你知道了前几把,就应该很容易猜到了。它们还具有*tstr变体,其中t用于指示这可能是常规字符或宽字符,这取决于项目中是否启用了Unicode。如果定义了unicode,lpctstr解析为lpcwstr,否则lpcstr解析为lpcwstr。

    所以,实际上,在处理字符串时,您只需要知道我在顶部列出的两种类型。其余的只是用于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::字符串 类,因为与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.
    
        2
  •  2
  •   yesraaj    15 年前

    这里是一个 article 这包括了你主要需要的东西

        3
  •  1
  •   jon hanson    15 年前
    OutputDebugStringW (myString.c_str ());
    
        4
  •  0
  •   PowerApp101    15 年前

    欢迎使用C++;

    您可以创建一个包装函数来接受 std::string . 然后在函数中提取C样式的字符串并传递给 OutputDebugStringW .

        5
  •  0
  •   Dario    15 年前

    std::wstring std::string 只是…的别名 std::basic_string<wchar_t> std::basic_string<char> .

    两者都有 .c_str() -返回常规C字符串指针的方法( LPCWSTR 以及一个采用C字符串的构造函数。

        6
  •  0
  •   drby    15 年前

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