gpt4 book ai didi

c - 网络编程中char数组的问题

转载 作者:行者123 更新时间:2023-11-30 14:29:00 26 4
gpt4 key购买 nike

我有以下内容:节点ID = abcde.abc.edu_12345我需要附加下划线和 time() 返回的 10 位值来创建以下内容:节点安装 ID = abcde.abc.edu_12345_1016320007其中 1016320007 是 time() 返回的 10 位数字值。我正在尝试以下代码,但它似乎不起作用:

#define NODE_ID_LENGTH 20
#define NODE_INST_ID 31
char nodeID[NODE_ID_LENGTH]
char node_inst_ID[NODE_INST_ID];
int main()
{
/*
Building of nodeID is a bit complex. So its hard to put all the code here. But printing the following at this point gives this
for(int i = 0; i < NODE_ID_LENGTH; i++)
{
printf("%c", nodeID[i]);
}
gives
abcde.abc.edu_12345
If you need to know any more info about nodeID, I can post the print out of things that you suggest.
*/

long int seconds = time(NULL);
char buf[10];
sprintf(buf, "%ld", seconds);
snprintf(&node_inst_ID[0], 20, "%s", &nodeID[0]);
node_inst_ID[20] = '_';
node_inst_ID[21] = '\0';
cout<<"Node instance ID = "<<node_inst_ID<<endl;

/*
I havent yet added the code for appending the time stamp. But I am expecting a print out for the above code like this:
Node instance ID = abcde.abc.edu_12345_
But the code is printing only
Node instance ID = abcde.abc.edu_12345
It is not adding the underscore at the end.
*/
}

谁能指出错误是什么?提前致谢。

最佳答案

snprintf(&node_inst_ID[0], 20, "%s", &nodeID[0]);
node_inst_ID[20] = '_';
node_inst_ID[21] = '\0';

这里假设字符串的长度正好是 20 个字符 - 但事实并非如此。试试这个:

snprintf(&node_inst_ID[0], 20, "%s", &nodeID[0]);
strcat(node_inst_ID, "_"); // strcat is safe in this context, usually you should use strncat.

编辑:如果您仍然想使用 snprintf,简单的方法是:

int len = strlen(node_inst_ID);
snprintf(node_inst_ID + len, sizeof(node_inst_ID) - len, "%whatever", the, args);

关于c - 网络编程中char数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5305565/

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