c++ - 将 char[] 附加到具有特定长度的 std::string

标签 c++ string serial-port

我想从串行端口连接接收一个完整的字符串。 接收函数给我一个 char[] 和读取字符的值。所以我想将所有读取的字符添加到 std::string 直到 \r\n 字符。 这是我的代码,异常(exception)是在附加处:

    //----- CHECK FOR ANY RX BYTES -----
    if (uart0_filestream != -1)
    {
        // Read up to 255 characters from the port if they are there
        unsigned char rx_buffer[256];
        int rx_length = read(uart0_filestream, (void*)rx_buffer, 255);      //Filestream, buffer to store in, number of bytes to read (max)
        if(rx_length > 0){
            std::string result = "";
        //  res = "";
            while (rx_length > 0)
            {
                result.append(*rx_buffer, 0, rx_length);
                rx_length = read(uart0_filestream, (void*)rx_buffer, 255);
            }
            std::cout << "rec" << result << std::endl;
        }

    }

有人知道如何解决这个问题吗?

最佳答案

改变这个

result.append(*rx_buffer, 0, rx_length);

对此

result.append(rx_buffer, 0, rx_length);

并确保你有 #include <string>在您的 CPP 源文件中。

关于c++ - 将 char[] 附加到具有特定长度的 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33334321/

相关文章:

c - 如何在C中读写串口数据,open函数的问题

serial-port - 如何在C程序中通过串行终端读取二进制数据?

c++ - QSerialPort 和发送字节(值 > 127?)

c++ - 在使用 vector 和迭代器时与 const 行为作斗争

c++ - 通过指针从c++中的函数返回数组,但是程序如何知道数组大小?

android - 以后如何为 Ar 增强图像数据库加载图像?

c++ - 在特定位置将 char 附加到 std::vector<string>

c - 字符串参数条件

c++ - 不能在 Qt 中使用 libclang

java - 如何从 main() 访问字符串数组的元素