c++ - 字符串连接错误

标签 c++ string winapi

<分区>

编译以下代码...

#define UNICODE
#include<wchar.h>
#include<windows.h>
#include<string>

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,int nCmdShow)
{
    LPWSTR str1=L"vishal ";
    LPWSTR str2=L"nechwani";
    LPWSTR str3=str1 + str2;
    MessageBox(NULL,str3,str3,MB_OK);
    return 0;
}

...产生此错误:

error==>error: invalid operands of types 'LPWSTR {aka wchar_t*}' and 'LPWSTR {aka wchar_t*}' to binary 'operator+'

为什么我不能像这样连接两个字符串?

最佳答案

LPWSTR 是指向宽字符数组的指针。它不是带有 + 重载的类,因此您不能将 LPWSTR 与 + 连接起来。考虑改用 wstring

#define UNICODE
#include<windows.h>
#include<string>
int main()
{
    std::wstring str1(L"vishal ");
    std::wstring str2(L"nechwani");
    std::wstring str3 = str1 + str2;
    MessageBox(NULL, str3.c_str(), str3.c_str(), MB_OK);
    return 0;
}

如果您必须忍受 c 风格的字符串,请使用 wcscat,但不要忘记为 str3 预分配存储。

编辑:以愚蠢的方式做这件事

这是愚蠢的方法,因为看看你必须做的所有额外工作:

#define UNICODE
#include<cwchar>
#include<windows.h>

int main()
{
    LPCWSTR str1=L"vishal "; // note LPCWSTR. L"vishal " provides a constant array
                             // and it should be assigned to a constant pointer
    LPCWSTR str2=L"nechwani";

    // find out how much space we need
    size_t len = wcslen(str1) + // length string 1
                 wcslen(str2) + // length string 2
                 1; // null terminator. Can't have a c-style string without one

    LPWSTR str3 = new wchar_t[len]; // allocate space for concatenated string
                                    // Note you could use a std::unique_ptr here, 
                                    // but for smurf's sake just use a wstring instead
    str3[0] = L'\0'; // null terminate string

    //add string 1 and string 2 to to string 3
    wcscat(str3,str1);
    wcscat(str3,str2);

    MessageBox(NULL,str3,str3,MB_OK);
    delete[] str3; // release storage allocated to str3
    return 0;
}

被这个烂摊子弄糊涂并不丢脸。一团糟。

wcsncat 可能不是在这里使用的正确工具。要正确显示连接的字符串,您必须调整缓冲区大小以使其太大而无法截断或分配一个足够大的缓冲区以包含该字符串。我选择分配一个足够大的缓冲区。另请注意,wcsncat 仍然可以超出放置空终止符的缓冲区末尾,因此 count 参数不得比缓冲区大小小 1。

wstring 为您完成所有这些废话,并免费添加许多其他有用的操作。没有充分的理由不使用 string 来避免 string 是愚蠢的。别傻了。

关于c++ - 字符串连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48066970/

相关文章:

带嵌入式服务器的 C++ Web 框架?

javascript - 基于 startsWith() 和 endsWith() 连接字符串

ios - Swift - 使用哪些类型? NSString 或字符串

winapi - 调试 WIN32 焦点错误

c# - 获取任务栏中所有窗口的句柄

c++ - C++ 中的 volatile unsigned *

c++ - 多线程性能 std::string

c++ - 在 64 位机器中无法使用 getsystemdirectory() 获取正确的路径

mysql - 返回 MySQL 数据库中最小长度的字符串

winapi - 在 WindowsNT(最近的 x86 版本,Vista 和 Win7)下从用户模式切换到内核模式时,线程做了什么?