【问题标题】:problem with char arrays in network programming网络编程中的字符数组问题
【发布时间】:2011-03-14 22:49:36
【问题描述】:

我有以下几点: 节点ID = abcde.abc.edu_12345 我需要附加下划线和 time() 返回的 10 位值来创建以下内容: node_inst_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. 
    */
}

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

【问题讨论】:

    标签: c arrays networking network-programming char


    【解决方案1】:
    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);
    

    【讨论】:

    • 谢谢。使用 strcat 有效。另外,如何打印出 char 数组中的实际数据?例如我什至想打印出我在数组末尾有一个 '\0' 。但是如果我使用 printf("%c", char_array[LIMIT]);它不会打印出'\0'。
    • 我可以通过在 printf 中使用 %x 找到一些东西。 printf(%x, char_buf[i]);并递增 i 为 '\0' 打印出 0
    【解决方案2】:

    您已将下划线硬连线到 node_inst_ID 的索引 20,但它只包含 18 个字符和空终止符:

    0123456789012345678
    abcde.abc.edu_12345
    

    由于您没有覆盖空终止符,因此当您打印结果时,打印输出会停止。不要假设字符串的位置和长度;相反,使用字符串库函数来操作它们。

    【讨论】:

      【解决方案3】:

      nodeID 只有 19 个字符长。所以它在位置 19 有一个 \0 终止符,您在 node_inst_ID 中制作的副本也是如此。然后你从位置 20 开始存储更多的东西,在终止的零字节之后。所以你的下划线在字符串的末尾。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多