problem with char arrays in network programming
I have the following: nodeID = abcde.abc.edu_12345 and I need to append the an underscore and a 10digit value returned by time() to create the following: node_inst_ID = abcde.abc.edu_12345_1016320007 where 1016320007 is the 10 digit value returned by time(). I am trying the following code but it doesnt seem to work:
#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
开发者_如何学CIt is not adding the underscore at the end.
*/
}
Can anyone point out what the mistake is? Thanks in advance.
snprintf(&node_inst_ID[0], 20, "%s", &nodeID[0]);
node_inst_ID[20] = '_';
node_inst_ID[21] = '\0';
This assumes that the string is exactly 20 characters long - it isn't. Try this:
snprintf(&node_inst_ID[0], 20, "%s", &nodeID[0]);
strcat(node_inst_ID, "_"); // strcat is safe in this context, usually you should use strncat.
EDIT: If you want to still use snprintf, the easy way is:
int len = strlen(node_inst_ID);
snprintf(node_inst_ID + len, sizeof(node_inst_ID) - len, "%whatever", the, args);
You've hardwired the underscore to be at index 20 of node_inst_ID, however it only contains 18 characters and the null terminator at that point:
0123456789012345678
abcde.abc.edu_12345
Since you are not overwriting the null terminator, that's where the printout stops when you print the result. Don't assume positions and lengths for strings; instead, use string library functions to manipulate them.
nodeID
is only 19 characters long. So it has a \0
terminator in position 19, and so does the copy you make in node_inst_ID
. Then you store some more stuff starting at position 20, after the terminating zero-byte. So your underscore is after the end of the string.
精彩评论