【问题标题】:Create a new string from an old one从旧字符串创建新字符串
【发布时间】:2012-11-27 02:47:22
【问题描述】:

我正在使用 C++(Windows 环境)。我有一个:

LPCWSTR mystring;

这行得通:

mystring = TEXT("Hello");

但是怎么做呢? :

mystring = ((((create a new string with text = the content which is in another LPCWSTR 'myoldstring'))))

提前非常感谢!

PS:

mystring = myoldstring; 

会起作用,但它不会创建一个新字符串,它会是同一个指针。我想创建一个新字符串!

【问题讨论】:

    标签: c++ windows string pointers copy


    【解决方案1】:
    LPTSTR mystring;
    mystring = new TCHAR[_tcslen(oldstring) + 1];
    _tcscpy(mystring, oldstring);
    
    ... After you are done ...
    
    delete [] mystring;
    

    这是一个完整的程序

    #include <tchar.h>
    #include <windows.h>
    #include <string.h>
    
    int main()
    {
        LPCTSTR oldstring = _T("Hello");
    
        LPTSTR mystring;
        mystring = new TCHAR[_tcslen(oldstring) + 1];
        _tcscpy(mystring, oldstring);
    
        // Stuff
    
        delete [] mystring;
    
    
    }
    

    它与cl /DUNICODE /D_UNICODE a.cpp 编译得很好

    我使用了tchar 宏。如果你不想使用它,那么

    #include <windows.h>
    #include <string.h>
    
    int main()
    {
        LPCWSTR oldstring = L"Hello";
    
        LPWSTR mystring;
        mystring = new WCHAR[wcslen(oldstring) + 1];
        wcscpy(mystring, oldstring);
    
        // Stuff
    
        delete [] mystring;
    
    
    }
    

    使用 cl a.cpp 编译良好​​p>

    【讨论】:

    • error C2440: '=' : impossible de convertir de 'LPCWSTR *' en 'LPCWSTR'我今天很倒霉!
    • @JosBas 我的代码中的小错误 - 已更正 - 不会给出此错误。
    • 新的 LPCWSTR 行!
    • 又报错了:(:error C2664: 'wcscpy' : impossible de convertir le paramètre 1 de 'LPCWSTR' en 'wchar_t *'
    • 您是否进行了我指出的第二次更改 - mystring 应该是 LPTSTRLPWSTR 而不是 LPCWSTR
    【解决方案2】:

    要使用 C++ 标准字符串,您需要包含 &lt;string&gt; 标头。由于您正在处理LPCWSTR(强调其中的W 部分),您正在处理宽字符,因此您希望使用宽字符串(即std::wstring 而不是std::string)。

    #include <string>
    #include <iostream>
    #include <windows.h>
    
    int main() { 
        LPCWSTR x=L"This is a string";
    
        std::wstring y = x;
        std::wcout << y;
    }
    

    【讨论】:

    • 我不知道为什么,但是用这个解决方案,有崩溃!
    • @JosBas:这表明您正在使用的标准库或代码中的其他地方存在问题。在这两者中,您代码中其他地方的问题对我来说似乎更有可能。我在一个稍微更完整的示例中进行了编辑,该示例应该编译并显示复制的字符串(无论如何它都对我有用)。如果它有效,您的问题可能在您的代码中的其他地方。
    • 如果我删除这一行,不会崩溃。如果我添加它,则会发生崩溃。我使用了另一个在其他地方使用的变量名,这样崩溃就不会来自其他任何地方。
    • @JosBas:这听起来像是具有未定义行为的相当典型的结果:一些看似无关的更改突然导致崩溃。如果没有看到您的其他代码,则无法猜测它可能来自哪里。当然,您的标准库总是有可能有缺陷——std::wstring 的测试可能不如std::string 好(但问题仍然很可能出在您的代码中) .
    【解决方案3】:

    怎么样

    string myNewString = std::string(myOldString);
    

    只需使用字符串库的复制构造函数。

    【讨论】:

    • 'string' : identificateur introuvable !(找不到string)我使用C++(没有.NET)
    • @JosBas #include &lt;string&gt; ... 然后确保正确使用 std 命名空间,无论是通过前缀(std::string 在上述两种情况之一中省略)或通过@987654327 @.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多