C++ Linux 套接字在字符 *msg 中添加变量
C++ Linux Sockets adding variable in char *msg
我正在尝试向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";
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将更多文件夹添加到c++include路径
- 如何将元素添加到数组的线程安全函数?
- QT通过C++添加映射QML项目
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 只能向C++添加一定数量的字符
- Qt和C++:将QLineEdit添加到QTabWidget中
- 将QIcon添加到QTableView单元格
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- 为什么除非添加括号,否则构造函数上的模板替换会失败?
- 将图像添加到资源文件夹UWP C++
- C++ Linux 套接字在字符 *msg 中添加变量