如何在忽略 null 的同时将数据从 char [] 复制到常量字符 *
How to copy data from char [] to const char * whilst ignoring null
所以我在尝试通过UDP套接字发送一些数据时遇到问题。我需要使用 sendto 函数发送数据包。但是,该函数要求数据采用常量字符 *buf 的形式;我遇到的问题是我的数据位于大小为 1206 的 Char [] 中,当我尝试转换数据时,转换在遇到 null 时停止。而且我的数据有很多空值!!
所以我的问题是,有没有办法将 char [] 转换为常量字符 *buf,同时阻止它终止 null?
我已经附上了我当前的代码和正在打印的数据:-
//法典:
#include "stdafx.h"
#include <iostream>
#include <winsock2.h>
#include <string>
#include <cstring>
#include <stdio.h>
#include <fstream>
#include <vector>
#include <time.h>
#define DEFAULT_BUFLEN 1248
#define DTTMFMT "%d/%m/%Y %H:%M:%S"
#define DTTMSZ 21
using namespace std;
int SockConnRes, SendByte;
int DataLen = 1248;
char buffer[1206];
string packet;
int main()
{
// LOTS OF UDP SOCKET CODE WAS HERE//
do {
SockConnRes = recvfrom(serverL, buffer, sizeof(buffer), NULL, (SOCKADDR *) &addr, &addrlen);
printf("byte: %dn", SockConnRes);
if (SockConnRes > 0)
{
MyFile << getDtTm (buff) << endl;
printf("Data: %sn", buffer);
MyFile << "String: ";
//For loop to print buffer data and to try and convert data into a
//string but string packet just turned into another array//
for (int printer = 0; printer < sizeof(buffer); printer++)
{
printf("%x ", (unsigned char)buffer[printer]);
MyFile << "" << (unsigned char)buffer[printer];
packet += (unsigned char)buffer[printer];
}
printf("n");
MyFile << endl;
const char *data = packet.c_str();
DataLen = sizeof(data);
printf("Data byte: %dn", DataLen);
cout << "String:" << data << endl; //PRINTING WHAT SHOULD BE STORED IN CONST CHAR *BUF
SendByte = sendto(IPemotion, data, DataLen, 0, (SOCKADDR *) &IPeService, (int)sizeof(IPeService));
printf("Sent byte: %dn", SendByte);
memset(buffer, 0, sizeof(buffer));
packet.clear();
Sleep(500);
}
else if (SockConnRes == 0)
{
printf("Connection Closedn");
}
else
{
printf("recv failed: %dn", WSAGetLastError());
}
} while(SockConnRes > 0);
MyFile.close();
closesocket(serverL);
WSACleanup();
return 0;
}
结果:图像显示由蓝色笔打印的字符串,红色显示 0 停止转换的位置任何帮助都非常感谢,谢谢!
您切断数据的原因不是因为空值,而是因为:
const char *data = packet.c_str();
DataLen = sizeof(data);
DataLen
是 4,因为指针的大小在您的情况下是 4 个字节,因此您只发送 4 个字节。
看到packet
是一个string
,你可以尝试像这样传递数据包的大小:
DataLen = packet.size();
相关文章:
- 使用strcpy将char数组的元素复制到另一个数组
- 使用动态分配将 char* 复制到另一个字符**
- 如何将 cv::Mat & Img 复制到未签名的 char* img?opencv
- 我可以使用istream_iterator将<char>一些 istream 内容复制到 std::string 中吗?
- char 和 char& 之间是否存在相对复制开销差异?
- 如何在忽略 null 的同时将数据从 char [] 复制到常量字符 *
- 如何将const char*复制到c 中的uint8_t []
- C - 从const char*复制到字符串
- 将矢量<char>复制到 2D 矢量 <string> c++
- C++将 char 复制到 char 数组(调试断言失败)时,字符串不是以 null 结尾的
- 将内存从char*复制到较大char*中的某个位置
- C++ 使用 char* 复制字符数组(无字符串库)
- 将 boost::array<char> 复制到 std::string
- 如何将char复制到char*向量中
- 将子字符串从char*复制到std::string的优雅方式
- 如何在c++中将数组char复制到字符串或int*(void*)中
- 方便地将 std::vector<unsigned char> 复制到输入流 (std::istream) 对象
- 从char*复制到char[]
- 将char复制到struct指针char
- 如何有效地将 std::vector<char> 复制到 std::string