【发布时间】:2014-11-12 11:02:40
【问题描述】:
我有一个字符串不是空终止的错误,虽然我不完全确定为什么。在代码的第二部分中使用 std::string 是我尝试解决此问题的尝试之一,尽管它仍然不起作用。
我的初始代码只是使用缓冲区并将所有内容复制到 client_id[]。比发生的错误。如果错误是正确的,这意味着我有 client_id 或者 theBuffer 没有空终止符。我很确定 client_id 没问题,因为我可以在调试模式下看到它。奇怪的是缓冲区也有一个空终止符。不知道出了什么问题。
char * next_token1 = NULL;
char * theWholeMessage = &(inStream[3]);
theTarget = strtok_s(theWholeMessage, " ",&next_token1);
sendTalkPackets(next_token1, sizeof(next_token1) + 1, id_clientUse, (unsigned int)std::stoi(theTarget));
里面 sendTalkPackets 是。我得到一个字符串不是在最后一行终止的。
void ServerGame::sendTalkPackets(char * buffer, unsigned int buffersize, unsigned int theSender, unsigned int theReceiver)
{
std::string theMessage(buffer);
theMessage += "0";
const unsigned int packet_size = sizeof(Packet);
char packet_data[packet_size];
Packet packet;
packet.packet_type = TALK;
char client_id[MAX_MESSAGE_SIZE];
char theBuffer[MAX_MESSAGE_SIZE];
strcpy_s(theBuffer, theMessage.c_str());
//Quick hot fix for error "string not null terminated"
const char * test = theMessage.c_str();
sprintf_s(client_id, "User %s whispered: ", Usernames.find(theSender)->second.c_str());
printf("This is it %s ", buffer);
strcat_s(client_id, buffersize , theBuffer);
【问题讨论】:
-
theMessage += "0";您是否期望这会添加一个空终止符?如果是这样,它不会。 -
此外,在这种情况下,不需要对这个 char 数组和指针进行任何操作。您可以完全使用
std::string,并且只有当函数调用const char*时,您最终才会使用c_str()成员函数来获取C 风格的字符串。 -
@PaulMcKenzie 是的,这实际上是我的一次尝试遗留下来的代码。现在我正在尝试使用字符串来操作它。
-
如果你真的想空终止字符串(无论如何都不需要),你会做
theMessage.push_back(0);