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

标签 c arrays networking network-programming char

我有以下内容: 节点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/

相关文章:

c - C中的Web服务器问题

c - 如何从一个 makefile 构建多个目标

c - 将表指针从 C 传递到汇编函数

arrays - 从数组中删除 NSTableView 中选定的对象

python - 如何用Python将不同类型的数据一起打包成二进制数据

c++ - 是否有通用方法从枚举 NetworkError 中获取网络错误字符串,或者我是否需要构建一个?

c - 释放三重指针

c++ - C++中的拆分函数

Android DatagramSocket错误信息: EADDRINUSE (Address already in use)

c++ - 处理 double 时模运算符的使用