C++ Linux 套接字在字符 *msg 中添加变量

C++ Linux Sockets adding variable in char *msg

本文关键字:msg 添加 变量 字符 Linux 套接字 C++      更新时间:2023-10-16

我正在尝试向send()添加一个插入变量。

这是代码:

string num;
// + num + is the reason for the error. Any work around or suggestions?
char *msg = "GET /index.php?num=" + num + " HTTP/1.1nhost: domain.comnn";
int len;
ssize_t bytes_sent;
len = strlen(msg);
bytes_sent = send(socketfd, msg, len, 0);

我收到错误:

test.cpp: In function âint main()â:
test.cpp:64: error: cannot convert âstd::basic_string<char, std::char_traits<char>, 
std::allocator<char> >â to âchar*â in initialization

--编辑--

我试图用msg.c_str修复它

cout << "send()ing message..."  << endl;
string msg = "GET /index.php?num=" + num + " HTTP/1.1nhost: domain.comnn";   
int len;
ssize_t bytes_sent;
len = msg.lenght(); //updated to this and still gives me an error.
bytes_sent = send(socketfd, msg.c_str, len, 0);

现在它给了我错误:

error: argument of type âconst char* (std::basic_string<char, std::char_traits<char>, 
std::allocator<char> >::)()constâ does not match âconst char*â

"stuff" + num + "more stuff"不会按照您的期望执行。 即使您要将str转换为字符指针,即使C++允许您将字符指针添加到一起,它最终也会做完全错误的事情。

(作为参考,C++不允许将指针添加在一起,因为结果没有任何意义。 指针仍然只是数字,添加两个字符指针基本上相当于0x59452448 + 0x10222250或类似的东西,这会返回一个指向某个可能甚至还不存在的位置的指针......

试试这个:

string msg = string("GET /index.php?num=") + num + " HTTP/1.1nhost: domain.comnn";
ssize_t bytes_sent = send(socketfd, msg.c_str(), msg.size(), 0);

std::string 不会隐式转换为 char* 。您需要使用 c_str .

理想情况下,您应该在应用程序中完全使用字符串(而不是 char*),直到 API 函数需要 char* 为止,此时您调用字符串上的 c_str 以获取要调用的函数的 const char*。

您在第三行未初始化的地方使用了num。也许你想要:

std::string num;
std::string msg = "GET /index.php?num=" + num + " HTTP/1.1nhost: domain.comnn";