我想从串行端口连接接收一个完整的字符串。
接收函数给我一个 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/