0
read(client_sockfd, &chID, 4);
char newID[4];
for(int i; i<5; i++){
     newID[i] = chID[i];
}

I'm reading char chID[4] over a socket. I want to put the first 4 characters into newID. Above is what I've tried, but I get some weird output when I copy newID into a string and print it out. Any guidance?

anscmc
  • 23
  • 2

3 Answers3

1

You declare i within the for loop without initialising it. This is the reason you get 'weird values'. In order to rectify, you need to write:

for(int i=0; i<5; i++)

Hope this helps!

  • Is there a difference or any benefit to either this method or memcpy? Or are they doing the same thing? – anscmc May 02 '16 at 03:36
  • @anscmc You are good to use both. I posted the above answer in response to the specific code you are using and to point out why you are getting *weird values*. Which approach would be better depends on what exactly you are trying to accomplish. Additional details [here](http://stackoverflow.com/questions/4729046/memcpy-vs-for-loop-whats-the-proper-way-to-copy-an-array-from-a-pointer). –  May 02 '16 at 03:46
0

Just copy the bytes:

memcpy(newID, chID, 4);
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

One more note that it seems some people have overlooked here: if chId is length 4 then the loop bounds are i=0;i<4. That way you get i=0,1,2,3. (General programming tip, unroll loops in your head when possible. At least until you are satisfied that the program really is doing what you meant it to.)

NB: You're not copying chId into a string. You're copying it into a char array. That may seem like semantics, but "string" names a data type in C++ which is distinct from an array of characters. Got it right in the title, wrong in the question description.

Eric
  • 79
  • 1
  • 3
  • Thanks, Eric. About the string convert: I didn't post that code; sorry that wasn't clear. After this loop I was using "string str(newID)" to copy newID into str, then printing it out with cout. I think with the three answer I've received, I've found my solution. Thank you! – anscmc May 02 '16 at 14:34