C++ 从套接字读取到 std::string [英] C++ Read From Socket into std::string

查看:25
本文介绍了C++ 从套接字读取到 std::string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C++ 编写一个使用 C 套接字的程序.我需要一个函数来接收我想返回一个字符串的数据.我知道这行不通:

I am writing a program in c++ that uses c sockets. I need a function to receive data that I would like to return a string. I know this will not work:

std::string Communication::recv(int bytes) {
    std::string output;
    if (read(this->sock, output, bytes)<0) {
        std::cerr << "Failed to read data from socket.\n";
    }
    return output;
}

因为 read()* 函数采用 char 数组指针作为参数.在这里返回字符串的最佳方法是什么?我知道理论上我可以将数据读入字符数组,然后将其转换为字符串,但这对我来说似乎很浪费.有没有更好的办法?

Because the read()* function takes a char array pointer for an argument. What is the best way to return a string here? I know I could theoretically read the data into a char array then convert that to a string but that seems wasteful to me. Is there a better way?

*如果有更合适的替代方案,我实际上并不介意使用 read() 以外的其他东西

*I don't actually mind using something other that read() if there is a more fitting alternative

这是 pastebin 上的所有代码,它们应该会在一周内到期.如果到那时我还没有答案,我会重新发布:http://pastebin.com/HkTDzmSt

Here is all of the code on pastebin which should expire in a week. If I don't have an answer by then I will re-post it: http://pastebin.com/HkTDzmSt

[更新]

我也尝试使用 &output[0] 但得到的输出包含以下内容:

I also tried using &output[0] but got the output contained the following:

jello!
[insert a billion bell characters here]

果冻!"是发送回套接字的数据.

"jello!" was the data sent back to the socket.

推荐答案

这里有一些功能可以帮助您完成您想要的工作.它假设您只会从套接字的另一端接收 ascii 字符.

Here are some functions that should help you accomplish what you want. It assumes you'll only receive ascii character from the other end of the socket.

std::string Communication::recv(int bytes) {
    std::string output(bytes, 0);
    if (read(this->sock, &output[0], bytes-1)<0) {
        std::cerr << "Failed to read data from socket.\n";
    }
    return output;
}

std::string Communication::recv(int bytes) {
    std::string output;
    output.resize(bytes);

    int bytes_received = read(this->sock, &output[0], bytes-1);
    if (bytes_received<0) {
        std::cerr << "Failed to read data from socket.\n";
        return "";
    }

    output[bytes_received] = 0;
    return output;
}

打印字符串时,一定要使用cout <<output.c_str() 因为字符串会覆盖 operator<< 并跳过不可打印的字符,直到达到大小.最终,您还可以在函数末尾将大小调整为接收到的大小,并能够使用正常的 cout.

When printing the string, be sure to use cout << output.c_str() since string overwrite operator<< and skip unprintable character until it reaches size. Ultimately, you could also resize at the end of the function to the size received and be able to use normal cout.

正如评论中所指出的,首先发送大小也是一个好主意,以避免字符串类可能进行不必要的内存分配.

As pointed out in comments, sending the size first would also be a great idea to avoid possible unnecessary memory allocation by the string class.

这篇关于C++ 从套接字读取到 std::string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆