简体   繁体   中英

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?

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!

只需复制字节:

memcpy(newID, chID, 4);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM