gpt4 book ai didi

c++ - 无法按预期打印 char 数组

转载 作者:行者123 更新时间:2023-11-28 06:22:00 25 4
gpt4 key购买 nike

#include <fstream>
#include<iostream>
#include<cstring>
using namespace std;

class Address {
public:
char addr[6];
Address() {}
Address(string address) {
size_t pos = address.find(":");
int id = stoi(address.substr(0, pos));
short port = (short)stoi(address.substr(pos + 1, address.size()-pos-1));
memcpy(addr, &id, sizeof(int));
memcpy(&addr[4], &port, sizeof(short));
}
};
enum MsgTypes{
JOINREQ,
JOINREPLY,
DUMMYLASTMSGTYPE,
HEARTBEAT
};

/**
* STRUCT NAME: MessageHdr
*
* DESCRIPTION: Header and content of a message
*/
typedef struct MessageHdr {
enum MsgTypes msgType;
}MessageHdr;

typedef struct en_msg {
// Number of bytes after the class
int size;
// Source node
Address from;
// Destination node
Address to;
}en_msg;

//class Testing{

void send(Address *myaddr, Address *toaddr, char *data, int size);
int main()
{
MessageHdr *msg=new MessageHdr();
size_t msgsize = sizeof(MessageHdr) + sizeof(Address) + sizeof(long) + 1;
msg=(MessageHdr *)malloc(msgsize*sizeof(char));
int id=233;
short port =22;
long heartbeat=1;
msg=(MessageHdr *)malloc(msgsize*sizeof(char));
string s=to_string(id)+":"+to_string(port);
string s1=to_string(id+1)+":"+to_string(port+1);
cout<<s<<'\n';
cout<<s1<<'\n';
Address *addr= new Address(s);
for (int i = 0; i < 6; i++)
cout << addr->addr[i];

Address *toaddr= new Address(s1);
msg->msgType = JOINREQ;
//cout<<(char *)msg->msgType;
memcpy((char *)(msg+1), addr, sizeof(addr));
memcpy((char *)(msg+1) + 1 + sizeof(addr), &heartbeat, sizeof(long));
send(addr, toaddr, (char *)msg, msgsize);
return 0;
}

void send(Address *myaddr, Address *toaddr, char *data, int size) {
cout<<"inside send"<<'\n';
en_msg *em;
//static char temp[2048];

em = (en_msg *)malloc(sizeof(en_msg) + size);
em->size = size;

memcpy(&(em->from), &(myaddr), sizeof(em->from));
memcpy(&(em->to), &(toaddr), sizeof(em->from));
memcpy(em + 1, data, size);
cout<<(char *)(em+1);
}

这是我的程序,我正在尝试检查存储在我的 char 数组中的地址。但是在打印数组时,它给出了一些奇怪的输出。打印 s 和 s1 的值后出现两个奇怪的符号。 我试图将 id:port 存储在地址类的 char 数组中,但看起来没有成功。请帮忙

我指的用于打印的代码在主函数中。主函数下方大约十行。

比如说,我的id是233,端口是22,地址是233:22,我想取回233:22打印出来。我该怎么做?

提前致谢:)

最佳答案

问题出在这一行:

cout << addr->addr[i];

由于 addr->addr 是一个 char 数组,每个元素将被打印为它所代表的字符。如果您更愿意打印每个的整数值,只需先将其转换为 int

cout << static_cast<int>(addr->addr[i]); // or old-fashioned: (int)addr->addr[i];

关于c++ - 无法按预期打印 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29172529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com