我使用memcpy将特定数量的字符从char数组复制到char *。但是,当我读到这个字符*总是垃圾在最后。
我使用libssh2库向我的raspberry pi发送命令并接收输出。
libssh2_channel_read将返回输出int x的字符数,输出文本将位于char buffer[32]上。
我正在使用的代码:
char buffer[32];
int x = libssh2_channel_read(channel, buffer, sizeof(buffer));
char * output = (char *)malloc(sizeof(char)*x);
memcpy(output, buffer, x-2); // x - 2 because of "\r\n"
libssh2_channel_free(channel);
channel = NULL;
cout << output << endl;产出实例:
0══²²²²我只想要0
发布于 2017-07-05 13:01:55
欢迎来到C++。
您正在复制您所关心的值,而不是终止“\0”字符。假设x是有效的(即:x>3和x <= sizeof(缓冲区)),您可以这样说:
output[x - 2] = '\0';在调用memcpy()之后,您应该得到您所期望的。
但是,当您处理这样的通信和缓冲区时,您需要小心并检查所有内容。
发布于 2017-07-05 13:09:39
我认为您不应该在这里使用原始数组和memcpy等。
您最好使用C++标准库中的容器:
示例:
std::vector<char> buffer(32);
int x = libssh2_channel_read(channel, &buffer[0], buffer.size());
// probably x will be smaller or equal the current size of the buffer
buffer.resize(x);
// if it's a string, why not have it as a std::string
std::string data(buffer.begin(), buffer.end());
std::cout << data << '\n';发布于 2017-07-05 13:17:36
使用std::string:
char buffer[32];
int x = libssh2_channel_read(channel, buffer, sizeof(buffer));
std::string output{ buffer, buffer + x - 2 };
libssh2_channel_free(channel);
channel = NULL;
cout << output << endl;https://stackoverflow.com/questions/44926886
复制相似问题