anscmc
anscmc

Reputation: 23

How can I copy the first i amount of characters in a character array into another character array in C++?

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?

Upvotes: 0

Views: 346

Answers (3)

Eric
Eric

Reputation: 79

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.

Upvotes: 0

user3576734
user3576734

Reputation:

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!

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249642

Just copy the bytes:

memcpy(newID, chID, 4);

Upvotes: 0

Related Questions