通过传递参数进行字符串连接

String concatenation by passing a parameter

这是我的:

WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
        cout << "WSAStartup failed.\n";
        system("pause");
    }
    SOCKET Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    struct hostent *host;
    host = gethostbyname("myserverip");
    SOCKADDR_IN SockAddr;
    SockAddr.sin_port=htons(80);
    SockAddr.sin_family=AF_INET;
    SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
    cout << "Connecting...\n";
    if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0){
        cout << "Could not connect";
        // system("pause");
    }
    cout << "Connected.\n";
    send(Socket,"GET / HTTP/1.1\r\nHost: myserverip\r\nConnection: close\r\n\r\n", strlen("GET / HTTP/1.1\r\nHost: myserverip\r\nConnection: close\r\n\r\n"),0);
    char buffer[10000];
    int nDataLength;
    while ((nDataLength = recv(Socket,buffer,10000,0)) > 0){        
        int i = 0;
        while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
            cout << buffer[i];
            i += 1;
        }
    }
    closesocket(Socket);
    WSACleanup();

(此代码在循环内)。我想在我将使用变量发送的 header 中设置我的 server-host。这实际上是我试图做的:

WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
    cout << "WSAStartup failed.\n";
}
SOCKET Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct hostent *host;
host = gethostbyname(myhost);
SOCKADDR_IN SockAddr;
SockAddr.sin_port = htons(80);
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0) {
    return 1;
}
send(Socket, "GET / HTTP/1.1\r\nHost: " + myhost + "\r\nConnection: close\r\n\r\n", strlen("GET / HTTP/1.1\r\nHost: " + myhost + "\r\nConnection: close\r\n\r\n"), 0);
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0) {
    int i = 0;
    while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
        cout << buffer[i];
        i += 1;
    }
}
closesocket(Socket);
WSACleanup();

这段代码也在一个循环中。全局变量声明如下:

string myhost;

但我无法让它工作,尤其是在这一行:

send(Socket, "GET / HTTP/1.1\r\nHost: " + myhost + "\r\nConnection: close\r\n\r\n", strlen("GET / HTTP/1.1\r\nHost: " + myhost + "\r\nConnection: close\r\n\r\n"), 0);

我该如何解决这个问题?我是 C++ 初学者。

使用类型为 std::string 的变量,然后使用 std::string::c_str() 从中获取可用于调用 send.

的 C 字符串
std::string str = "GET / HTTP/1.1\r\nHost: ";
str += myhost;
str += "\r\nConnection: close\r\n\r\n";

send(Socket, str.c_str(), str.size(), 0);