开发者

Visual C++ copy char array into char array

开发者 https://www.devze.com 2023-03-10 11:01 出处:网络
Need help开发者_如何学C with copying array object to a temp array object using a for loop (see code + comments below)..... Thanks in advance!!!!

Need help开发者_如何学C with copying array object to a temp array object using a for loop (see code + comments below)..... Thanks in advance!!!!

    int counter;
    char buffer[] = "this is what i want 0 ignore the rest after the zero"; //
    char command[sizeof(buffer)];

    for ( counter = 0; counter < sizeof(buffer); counter++ ){
        if ( buffer[counter] == '0' ){      
            break; // Exit loop (Should Exit)
        }
        command[counter] = buffer[counter]; // Copy array object into new array
        printf("%c",command[counter]);
    }
    printf("\n",NULL);
    printf("%s\n",command); // However when I print it contains the whole array this shouldnt be is should only contain "this is what i want "


Strings are terminated by a '\0' character

So simply add after the for loop

command[counter]=0;

(when you exit the for loop the value of counter will be "pointing" at the last character's place in the command variable)


http://ideone.com/haCBP

Your code is working fine:

output:
this is what i want
this is what i want

Edit: That being said, you need to initialize your output buffer:

char command[sizeof(buffer)]={}; // now the string will be null-termiated
                                 // no matter where the copy ends


There's a bit easier way to do the job:

sscanf(buffer, "%[^0]", command);

This copies the right data and assures it's properly terminated, all in one (reasonably) simple operation.

Note, that in C++ you probably want to use std::string instead of NUL-terminated arrays of char for situations like this though.


counter = 0;
while (buffer[counter] != '0'){
command[counter] = buffer[counter];
counter ++;
}

try something like this...but add control to make sure you do not excide the buffer/command dimension!

0

精彩评论

暂无评论...
验证码 换一张
取 消