我应该阅读每个字符直到它到达 \n 字符,将它们全部连接在一起并返回还是有更好的方法?我应该为此使用 std::string 还是 char ?
我尝试了以下两个示例,但我需要将它们作为单独的行阅读
示例 1:
std::string sockread()
{
std::string s;
s.resize(DEFAULT_BUFLEN);
int result = recv(m_socket, &s[0], DEFAULT_BUFLEN, 0);
if (result > 0) {
return s;
} else if (result == 0) {
connected = false;
} else {
std::cout << "recv failed with error " << WSAGetLastError() << "\n";
}
throw std::runtime_error("Socket connection failed!");
}
示例 2:
char sockread(void)
{
int result;
char buffer[DEFAULT_BUFLEN];
result = recv(m_socket, buffer, DEFAULT_BUFLEN, 0);
if (result > 0) {
return *buffer;
}
else if (result == 0)
{
connected = false;
return *buffer;
}
else {
printf("recv failed with error: %d\n", WSAGetLastError());
return *buffer;
}
}