C++中的多个字符

Multiple chars in C++

本文关键字:字符 C++      更新时间:2023-10-16

如何正确连接DataBuffer?从PHP到C++并不容易,哈哈,我到底做错了什么?

while(true) {
    DWORD TitleID = XamGetCurrentTitleId();
    char DataBuffer[] = "Here's the current title we're on : ";
    char DataBuffer[] = (DWORD)TitleID;
    char DataBuffer[] = "nn";
    DWORD dwBytesToWrite = (DWORD)strlen(DataBuffer);
}

在C++中,通常使用std::string类型。要从多个输入创建一个字符串,特别是如果它们一开始不是全部字符串,我们使用ostringstream

所以你可以建立这样的信息:

while(true) {
    DWORD TitleID = XamGetCurrentTitleId();
    std::ostringstream titleMessageSS;
    titleMessageSS << "Here's the current title we're on : "
                   << TitleID // already a DWORD, no need for the cast
                   << "nn";
    std::string titleMessage = titleMessageSS.str(); // get the string from the stream
    DWORD dwBytesToWrite = (DWORD)titleMessage.size();
    // You don't do anything with this, so can't help you with how to write the string...
}

现在,如果使用WriteToFile,则需要从字符串中获取一个char指针。使用titleMessage.c_str()执行此操作。

或者,您可以使用+来构建std::string,再加上std::to_string来转换TitleID(这样您就可以用string+)。

尽管PHP可以自动转换为字符串,但C++没有(除了某些情况)。你(通常)必须明确你的类型。幸运的是,C++11提供了std::to_string,这使得这变得容易多了:

while(true) {
    DWORD TitleID = XamGetCurrentTitleId();
    std::string DataBuffer = "Here's the current title we're on : " 
                           + std::to_string(TitleID)
                           + "nn";
    DWORD dwBytesToWrite = static_cast<DWORD>(DataBuffer.size());
    /* ... */
}