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

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

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

    或者,下一次C++编译器为了在两种任意字符串类型之间转换而扭动你的手臂来惹你生气时,如何不自杀或杀人?

    我很难用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'
    

    更新

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

    有两种内置字符串类型:

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

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

    或者换句话说,a constwchar_t* .

    或者换句话说,a char* (非const)。

    所以说真的,在处理字符串时,你只需要知道我在顶部列出的两种类型。其余的只是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++ 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.
    
        2
  •  2
  •   yesraaj    17 年前

    这是一 article

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

    std::string OutputDebugStringW .

        5
  •  0
  •   Dario    17 年前

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

    .c_str() LPCWSTR 等等)和采用C字符串的构造函数。

        6
  •  0
  •   drby    17 年前

    你可能想看看 CStdString 这是一个跨平台的标准C++CString实现,可以很容易地转换为大多数其他字符串类型。几乎所有与字符串相关的麻烦都消失了,它只是一个头文件。