簡體   English   中英

Visual C++ 將字符數組復制到字符數組中

[英]Visual C++ copy char array into char array

在使用 for 循環將數組 object 復制到臨時數組 object 時需要幫助(請參見下面的代碼 + 注釋).....提前致謝!!!!

    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 "

字符串以'\0'字符結尾

所以只需在 for 循環之后添加

command[counter]=0;

(當您退出 for 循環時, counter的值將“指向” command變量中最后一個字符的位置)

http://ideone.com/haCBP

您的代碼運行良好:

output:
這就是我要的
這就是我要的

編輯:話雖如此,您需要初始化 output 緩沖區:

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

有一種更簡單的方法可以完成這項工作:

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

這會復制正確的數據並確保它被正確終止,所有這些都在一個(合理的)簡單操作中完成。

請注意,在 C++ 中,您可能希望在這種情況下使用std::string而不是以 NUL 結尾的 arrays 字符。

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

嘗試這樣的事情......但添加控制以確保您不會超出緩沖區/命令維度!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM