我在通过 TCP 网络发送字符串时遇到问题,其中字符串正在发送未输入的其他字符。
下面是我用来发送字符串的代码。
string input;
printf("Please input what you want to send...\n");
printf(">");
cin >> input;
const char* ch = (const char*)&input;
int lengthOfBytes = sizeof(input);
for (int i = 0; i < lengthOfBytes; i++)
{
n = send(socket_d, &*ch, 10, 0);
}
//Reading in characters.
if (ch == (const char*)'\r')
{
cout << "\n";
}
这是用于接收字符串的代码。
int n;
int count = 0;
char byte;
n = recv(socket_d, &byte, 1, 0);
if (n <= 0)
{
if (WSAGetLastError() != WSAEWOULDBLOCK)
{
cout << "Terminated " << WSAGetLastError() << "\n";
return;
}
}
else
{
cout << (char) byte;
if ((char) byte == '\r')
cout << "\n";
}
我在通过网络发送字符串时做错了什么?
最佳答案
您完全误解了如何从 std::string
对象访问字符串数据。您需要使用方法 std::string::data()
和 std::string::size()
来获取字符串数据本身,如下所示:
发件人:
std::string input;
std::cout << "Please input what you want to send...\n";
std::cout << "> ";
cin >> input;
n = send(socket_d, input.data(), input.size(), 0);
// check for errors here..
我没有 Windows,所以我的客户端代码可能与您需要的不同,但可能有点像这样:
接收方:
std::string s;
int n;
char buf[256];
while((n = recv(socket_d, buf, sizeof(buf), 0)) > 0)
s.append(buf, buf + n);
if(n < 0)
{
std::err << std::strerror(errno) << '\n';
return 1; // error
}
// use s here
std::cout << "received: " << s << '\n';
关于c++ - 在 C++ 中使用套接字通过网络发送字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31900493/