如何在忽略 null 的同时将数据从 char [] 复制到常量字符 *

How to copy data from char [] to const char * whilst ignoring null

本文关键字:char 复制 字符 常量 数据 null      更新时间:2023-10-16

所以我在尝试通过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();